Switch
Build a light/dark toggle and a three-way choice with “System” from what useColorScheme() returns, and keep markup from showing the wrong scheme before hydration.
On this page
Return value
const { scheme, preference, setPreference } = useColorScheme();Called in a Client Component, it returns three values decided by the provider in the root layout.
scheme: what is on screen,'light'or'dark'. It is the visitor’s choice if there is one, otherwise the provider’s default, which follows the OS setting when it is'system'.preference: what the visitor chose,'light','dark'or'system'. It is'system'while nothing is chosen.setPreference: stores a choice. Passing'system'clears the stored choice, and the provider’s default applies again.
The hook only reads what the provider decided. It never touches the class on <html> or localStorage. However many switches a page has, one provider decides for all of them, so they never disagree.
Two-way toggle
scheme-toggle.tsx'use client';
import { useColorScheme } from '@k8ordo/color-scheme';
export function SchemeToggle() {
const { scheme, setPreference } = useColorScheme();
const next = scheme === 'dark' ? 'light' : 'dark';
The opposite of `scheme`
return (
<button
onClick={() => {
setPreference(next);
}}
type="button"
>
Switch to {next}
</button>
);
}To flip between light and dark, store the opposite of scheme. preference does not tell you which way to go.
One press stores a choice, and from then on changing the OS setting no longer changes the scheme. To let visitors go back to following the OS, offer the three-way choice below.
The switch in this site’s header is this toggle.
Three-way choice with “System”
scheme-select.tsx'use client';
import { useColorScheme } from '@k8ordo/color-scheme';
import type { ColorSchemePreference } from '@k8ordo/color-scheme';
export function SchemeSelect() {
const { scheme, preference, setPreference } = useColorScheme();
return (
<select
onChange={(event) => {
setPreference(
event.currentTarget.value as ColorSchemePreference,
);
}}
value={preference}
>
<option value="system">System ({scheme})</option>
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
);
}To let the visitor choose to follow the OS as well, use preference as the value of the choice.
preference reads 'system' both for a visitor who never chose and for one who chose and went back.
Showing scheme beside the “System” option tells the visitor which scheme the OS setting gives right now.
Default
layout.tsx<head>
<ColorSchemeScript defaultPreference="dark" />
</head>
<body>
<ColorSchemeProvider defaultPreference="dark">
{children}
</ColorSchemeProvider>
</body>What a visitor who chose nothing gets is the defaultPreference. ColorSchemeScript applies it before the first paint and the provider after hydration, so give both the same value. Left out, it is 'system', which follows the OS setting.
The default is never stored. Change it later, and every visitor who has not chosen moves to the new default, while those who chose keep their choice. The inline script carries the same default, so the first paint starts from it too.
With a default other than 'system', a “System” option no longer says what it does: as a preference, 'system' means “nothing chosen”. Label it something like “Default” instead.
Pitfall
If a CSP allows the inline script by hash, give colorSchemeScriptHash() the same default. The default is written into the script, so changing it changes the hash. See CSP.
Before hydration
A server cannot read localStorage, so the provider renders the default there. With a 'system' default, the scheme it renders is 'light'. An icon or a label chosen from scheme keeps the server-rendered scheme until hydration.
The page’s colors are right from the first paint, because they follow the dark class that the inline script adds to <html>. Only markup chosen in React’s render is off, and there are two ways to fix it.
Switching with CSS
scheme-toggle.tsxexport function SchemeToggle() {
const { scheme, setPreference } = useColorScheme();
return (
<button
onClick={() => {
setPreference(scheme === 'dark' ? 'light' : 'dark');
}}
type="button"
>
<span className="dark:hidden">Switch to dark</span>
<span className="hidden dark:inline">Switch to light</span>
</button>
);
}Where CSS can do the switching, render both states and hide one with the dark: variant. The right one shows without waiting for hydration.
Note
This dark: is a variant declared to read the class on <html>. @k8ordo/ui’s tailwind.css already declares it. Tailwind CSS’s default dark: reads the OS setting, so with Tailwind CSS alone declare it as in “With Tailwind CSS alone” on Styling.
Rendering in the browser
scheme-toggle.tsx'use client';
import { useColorScheme } from '@k8ordo/color-scheme';
import { Suspense, use } from 'react';
import { browser } from 'react-dom';
import { MoonIcon, SunIcon } from './icons';
function SchemeIcon() {
use(browser('the stored preference is in localStorage'));
const { scheme } = useColorScheme();
return scheme === 'dark' ? <MoonIcon /> : <SunIcon />;
}
export function SchemeToggle() {
const { scheme, setPreference } = useColorScheme();
return (
<button
aria-label="Toggle color scheme"
onClick={() => {
setPreference(scheme === 'dark' ? 'light' : 'dark');
}}
type="button"
>
<Suspense fallback={<span className="size-5" />}>
<SchemeIcon />
</Suspense>
</button>
);
}Some things are awkward to switch with CSS, such as swapping an icon. For those, call use(browser()) in the component that renders the markup, and put it inside a <Suspense>. browser comes from react-dom.
Give the fallback an empty element the size of the icon, so the button keeps its size when the icon renders.
Pitfall
The <Suspense> is not optional: without it, the server render fails.
Toggle and choice demo
A toggle and a three-way choice wired to this site’s provider: either one changes the color scheme of the whole site.
Try it
- Choose “System”.
preferencebecomessystem, andschemeshows the scheme the OS setting gives. - Press “Switch to dark” or “Switch to light”. The opposite of what was on screen is stored, and the three-way choice moves to “Dark” or “Light”.
- Choose “System” again, then switch your OS’s appearance setting. Only
schemechanges;preferencestayssystem.