useDarkMode
Manages dark mode state with system preference detection, localStorage persistence, and automatic DOM class toggling.
Loading preview...
The useDarkMode hook resolves dark mode from the user's stored preference ('light' | 'dark' | 'system') and the OS prefers-color-scheme: dark media query, persists changes to localStorage, and toggles a class on document.documentElement.
Installation
Usage
Examples
Theme Switcher (Light / Dark / System)
Use enable, disable, and resetToSystem (or setPreference) to build a three-way theme selector.
Custom Storage Key and Class Name
Customize the localStorage key, class name, or disable automatic DOM class toggling when integrating with a custom theme provider.
API Reference
UseDarkModeOptions
Configuration options for storage persistence and DOM class syncing.
Property
Specification
defaultValue?uniondefault:false
Fallback dark mode state used during SSR and before hydration
Full Signature
storageKey?stringdefault:'color-scheme-preference'
localStorage key used to persist the color scheme preferenceFull Signature
darkClassName?stringdefault:'dark'
CSS class name toggled on the target element when dark mode is active
Full Signature
applyDarkClass?uniondefault:true
Whether to automatically toggle
darkClassName on the target elementFull Signature
target?uniondefault:document.documentElement
Target DOM element to apply
darkClassName toFull Signature
initializeWithValue?uniondefault:false
Read from
localStorage and matchMedia immediately on initial renderFull Signature
UseDarkModeReturn
Resolved dark mode state and helper functions returned by the hook.
Property
Specification
isDarkModeunion
Whether dark mode is currently active
Full Signature
preferenceColorSchemePreference
Current user preference (
'light', 'dark', or 'system')togglefunction
Toggles between
'light' and 'dark' preferencesFull Signature
enablefunction
Explicitly sets the preference to
'dark'Full Signature
disablefunction
Explicitly sets the preference to
'light'Full Signature
setPreferencefunction
Sets the color scheme preference directly
Full Signature
Parameters
preferenceColorSchemePreferenceresetToSystemfunction
Resets the preference back to
'system'Full Signature