Usage
import { usePrefersColorScheme } from "@servicetitan/anvil2";
function ThemeAwareComponent() {
const { mode } = usePrefersColorScheme();
return (
<div className={mode === "dark" ? "dark-theme" : "light-theme"}>
System prefers: {mode} mode
</div>
);
}
Return Value
| Property | Type | Description |
|---|
mode | "light" | "dark" | Current system color scheme preference |
Features
- Automatically updates when system preference changes
- Works with both modern and legacy browsers
- Handles SSR environments gracefully
Examples
Conditional Styling
function AdaptiveDiv() {
const { mode } = usePrefersColorScheme();
return (
<div
style={{
backgroundColor: mode === "dark" ? "#1a1a1a" : "#ffffff",
color: mode === "dark" ? "#ffffff" : "#000000",
}}
>
This div adapts to system preferences
</div>
);
}
With Theme Provider
function App() {
const { mode } = usePrefersColorScheme();
return (
<ThemeProvider mode={mode}>
<AppContent />
</ThemeProvider>
);
}
Image Variants
function Logo() {
const { mode } = usePrefersColorScheme();
return (
<img
src={mode === "dark" ? "/logo-light.svg" : "/logo-dark.svg"}
alt="Logo"
/>
);
}
Browser Support
The hook uses the prefers-color-scheme media query:
window.matchMedia("(prefers-color-scheme: dark)");
It supports both modern browsers (using addEventListener) and legacy browsers (using the deprecated addListener method).
SSR Considerations
When running on the server (where window is undefined), the hook defaults to "light" mode. The actual system preference will be detected on the client after hydration.Last modified on January 23, 2026