usePreferredColorScheme
prefers-color-scheme media query
usePreferredColorScheme uses window.matchMedia() to reactively track the user’s system color scheme preference. It returns "dark", "light", or "no-preference" based on the prefers-color-scheme media query. The value updates automatically when the user changes their system theme settings.
When to Use
- Detecting the user’s system theme to set an initial application color scheme
- Building theme-aware components that respect OS-level dark/light mode settings
- Providing a “system” option in theme selectors that follows the OS preference
Notes
- SSR-safe: Accepts a
defaultStateparameter (default:"no-preference") that is returned during server-side rendering. Nowindow.matchMediaaccess occurs on the server. - Reactive: Updates in real time when the user switches their system color scheme (e.g., enabling dark mode in OS settings).
- Related hooks: See also
usePreferredDarkfor a simpler boolean check,useColorModefor multi-theme management, anduseDarkModefor dark/light toggle with persistence.
Usage
Live Editor
function Demo() { const color = usePreferredColorScheme(); return <div>PreferredColorScheme: {color}</div>; };
Result
API
usePreferredColorScheme
Returns
ColorScheme: value of prefers-color-scheme media query
Arguments
| Argument | Description | Type | DefaultValue |
|---|---|---|---|
| defaultState | default value | ColorScheme | undefined | no-preference |
ColorScheme
Type
export type ColorScheme = 'dark' | 'light' | 'no-preference'