@k8ordo/color-scheme
Class-based dark mode switching for React
npm install @k8ordo/color-scheme @k8ordo/state zodsrc/routes/layout.tsx<html lang="ja" suppressHydrationWarning>
<head>
<ColorSchemeScript />
</head>
<body>
<ColorSchemeProvider>{children}</ColorSchemeProvider>
</body>
</html>theme-toggle.tsxconst { scheme, setPreference } = useColorScheme();
setPreference(scheme === 'dark' ? 'light' : 'dark');The right colors from the first paint
<ColorSchemeScript> is an inline script you put in <head>. It reads the saved preference and puts the dark class on <html> before the first paint.
A visitor who has not chosen gets the scheme that matches the OS setting.
Scheme switch demo
It uses the same useColorScheme() as the switch in the header.
- scheme
light- preference
system
Try it
- Press “Dark”, then reload the page. It comes back dark from the start.
- Press “System”, then change the appearance setting of your OS. The page follows it.
- Open this page in another tab and choose again there. This tab changes too.
A script a CSP can allow
A CSP can allow the inline script by the nonce you pass to ColorSchemeScript or by the script’s hash. No 'unsafe-inline' is needed.
colorSchemeScriptHash() computes the hash from the installed version’s script. Call it where the policy is written, and an update never leaves a stale value behind.
src/routes/layout.tsx<head>
<ColorSchemeScript nonce={nonce()} />
</head>csp.tsconst scriptSrc = ["'self'", await colorSchemeScriptHash()];Saving the chosen scheme
The choice is stored in localStorage through @k8ordo/state’s defineLocalState. Nothing is stored until the visitor chooses.
Change defaultPreference later, and every visitor who has not chosen follows it. A choice made in one tab applies to every open tab.
preference.tsxcolorSchemeState.storageKey;
// 'k8ordo-state:color-scheme'
localStorage.getItem(colorSchemeState.storageKey);
// '{"preference":"dark"}'
const [{ preference }] = useAppState(colorSchemeState);