useDarkMode
A hook that returns whether the user's device is in dark mode. It reactively updates when the mode changes, making it useful for conditionally styling your widget.
Import
import { useDarkMode } from "~lib/use-dark-mode";
API
const isDarkMode = useDarkMode();
Parameters
This hook takes no parameters.
Return Value
| Name | Type | Description |
|---|---|---|
isDarkMode | boolean | true if the user prefers dark mode, false otherwise |
Examples
Conditional Styling
import { useDarkMode } from "~lib/use-dark-mode";
const Widget = () => {
const isDarkMode = useDarkMode();
return (
<div
style={{
backgroundColor: isDarkMode ? "#1a1a1a" : "#ffffff",
color: isDarkMode ? "#e0e0e0" : "#333333",
padding: "20px",
}}
>
<h1>{isDarkMode ? "Dark Mode" : "Light Mode"}</h1>
</div>
);
};
Dynamic Icon Colors
Useful when rendering charts or icons that need to match the current color scheme:
import { useDarkMode } from "~lib/use-dark-mode";
const Widget = () => {
const isDarkMode = useDarkMode();
const strokeColor = isDarkMode ? "#ffffff" : "#000000";
const fillColor = isDarkMode ? "#4a9eff" : "#0066cc";
return (
<svg viewBox="0 0 100 100" width="200" height="200">
<circle
cx="50"
cy="50"
r="40"
fill={fillColor}
stroke={strokeColor}
strokeWidth="2"
/>
<text x="50" y="55" textAnchor="middle" fill={strokeColor} fontSize="14">
75%
</text>
</svg>
);
};
See Also
- useTheme - Returns the theme as a
"light" | "dark"string union instead of a boolean. UseuseThemewhen you need the string value, oruseDarkModewhen a boolean toggle is sufficient. - useResolution - Get the widget resolution for responsive layouts