useDarkMode
This hooks manages the state of your application's dark mode. Dark mode will default to the system dark/light mode settings set by the user via the prefers-color-scheme
media query, but can be overridden when the hook is initially called or when setIsDarkMode()
is invoked. The document root is also automatically given a dark-mode
class when dark mode is enabled.
Usage
-
Make sure you have
@ridgehkr/useful
installed in your application. If not, you can get started by following the installation instructions. -
Import
useDarkMode
into your component.
import { useDarkMode } from '@ridgehkr/useful'
Basic Example
App.jsx
import { useDarkMode } from '@ridgehkr/useful'
function DarkModeManager() {
const { isDarkMode, setIsDarkMode } = useDarkMode()
return (
<div>
<h1>{isDarkMode ? 'Dark Mode' : 'Light Mode'}</h1>
<button onClick={() => setIsDarkMode(!isDarkMode)}>
Toggle Dark Mode
</button>
</div>
)
}
API
Hook Signature
useDarkMode(initiallyDark?: boolean): DarkModeUsage
Parameters
initiallyDark
(optional): An initial value for the dark mode state. If not provided, the hook will default to the system-wide preference.
Property | Type | Required | Description |
---|---|---|---|
initiallyDark | boolean | no | Whether or not dark mode should be initially active |
Return Value
The hook returns a DarkModeUsage
object containing:
Property | Type | Description |
---|---|---|
isDarkMode | boolean | Whether or not dark mode is currently active |
setIsDarkMode | (darkMode: boolean) => void | Manually set the dark mode state |