Skip to Content
ohooks

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

pnpm dlx shadcn@latest add https://ohooks.vercel.app/r/useDarkMode.json

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
storageKey?
stringdefault:'color-scheme-preference'
localStorage key used to persist the color scheme preference
darkClassName?
stringdefault:'dark'
CSS class name toggled on the target element when dark mode is active
applyDarkClass?
uniondefault:true
Whether to automatically toggle darkClassName on the target element
target?
uniondefault:document.documentElement
Target DOM element to apply darkClassName to
initializeWithValue?
uniondefault:false
Read from localStorage and matchMedia immediately on initial render

UseDarkModeReturn

Resolved dark mode state and helper functions returned by the hook.

Property
Specification
isDarkMode
union
Whether dark mode is currently active
preference
ColorSchemePreference
Current user preference ('light', 'dark', or 'system')
toggle
function
Toggles between 'light' and 'dark' preferences
enable
function
Explicitly sets the preference to 'dark'
disable
function
Explicitly sets the preference to 'light'
setPreference
function
Sets the color scheme preference directly
resetToSystem
function
Resets the preference back to 'system'