usePreferredDark
React Hook that tracks dark theme preference
usePreferredDark uses window.matchMedia() with the (prefers-color-scheme: dark) media query to return a boolean indicating whether the user prefers a dark color scheme. The value updates automatically when the user toggles their system dark mode setting. This is a simpler alternative to usePreferredColorScheme when you only need a boolean.
When to Use
- Setting a default dark/light theme based on the user’s OS preference
- Conditionally applying dark-mode styles or class names in your components
- Determining the initial value for a theme toggle in your application
Notes
- SSR-safe: Accepts a
defaultStateparameter (default:false) that is returned during server-side rendering. Nowindow.matchMediaaccess occurs on the server. - Reactive: Updates immediately when the user changes their system dark mode preference.
- Related hooks: See also
usePreferredColorSchemefor"dark"/"light"/"no-preference"string values,useDarkModefor a toggle with localStorage persistence, anduseColorModefor multi-theme support.
Usage
Live Editor
function Demo() { const isDark = usePreferredDark(false); return <div>PreferredDark: {JSON.stringify(isDark)}</div>; };
Result
API
usePreferredDark
Returns
boolean: whether prefer dark
Arguments
| Argument | Description | Type | DefaultValue |
|---|---|---|---|
| defaultState | defaule value | boolean | undefined | - |