Back to Hooks

usePreferredColorScheme

usePreferredColorScheme.tsx

usePreferredColorScheme

THEME

// Detect user's OS/browser color preference (dark/light mode)

Quick Usage

const { colorScheme, toggleColorScheme } = usePreferredColorScheme({ autoApply: true });

Features

OS Detection
Auto Apply
Theme Toggle
Media Query

When to Use

Essential for theme switching, dark/light mode detection, and automatic UI theming based on user preferences.

Interactive Example

Current theme: Light

Browser does not support color scheme detection

Try this:

Change your OS theme settings and see the automatic detection in action!

Complete Example

import { usePreferredColorScheme } from '@usegrand/react-hokss';

function ThemeProvider({ children }) {
  const { colorScheme, toggleColorScheme, isSupported } = usePreferredColorScheme({
    autoApply: true,
    classNames: { light: 'light-theme', dark: 'dark-theme' }
  });

  return (
    <div className={colorScheme === 'dark' ? 'dark' : 'light'}>
      <button onClick={toggleColorScheme}>
        Switch to {colorScheme === 'dark' ? 'Light' : 'Dark'} Mode
      </button>
      {children}
    </div>
  );
}

API Reference

Parameters

optionsPreferredColorSchemeOptions

Configuration options for color scheme detection

options.defaultSchemeColorScheme

Default color scheme if no preference detected (default: 'light')

options.autoApplyboolean

Whether to automatically apply classes to document (default: false)

options.classNamesobject

CSS class names to apply for each scheme

Returns

PreferredColorSchemeResult

Object containing color scheme state and controls

colorScheme

Current color scheme ('light' or 'dark')

isPreferred

Whether current scheme is from user preference

isSupported

Whether media query is supported by browser

setColorScheme

Function to manually set color scheme

toggleColorScheme

Function to toggle between light and dark themes