How it works
When and where @k8ordo/color-scheme decides the scheme and toggles the dark class, and what it does and does not guarantee.
On this page
The rule
scheme.tsconst resolve = (
preference: ColorScheme | undefined,
defaultPreference: ColorSchemePreference,
systemDark: boolean,
): ColorScheme => {
const chosen =
preference ??
(defaultPreference === 'system' ? undefined : defaultPreference);
return chosen ?? (systemDark ? 'dark' : 'light');
};The scheme is decided in this order:
- If the visitor chose
'light'or'dark', that is the scheme. - Otherwise the provider’s
defaultPreferenceis used, when it is'light'or'dark'. - If the default is
'system'too,(prefers-color-scheme: dark)decides.
A stored value that is not a JSON object, or whose preference is neither 'light' nor 'dark', reads as nothing chosen. No other field is read.
“Nothing chosen” is not the OS setting saved on the first visit. With a 'system' default, a visitor who never chose follows the OS when its setting changes later.
Script and provider
(() => {
const s = (() => {
try {
const v = JSON.parse(
localStorage.getItem('k8ordo-state:color-scheme'),
);
return v !== null && typeof v === 'object' && !Array.isArray(v)
? v
: null;
} catch {
return null;
}
})();
const v = s && s.preference;
const p = v === 'dark' || v === 'light' ? v : 'system';
The `defaultPreference` goes here
if (
p === 'dark' ||
(p !== 'light' &&
matchMedia('(prefers-color-scheme: dark)').matches)
)
document.documentElement.classList.add('dark');
})();Above is the inline script written into the HTML when defaultPreference is 'system', formatted for reading. The script applies the rule before the first paint, and the provider applies it after hydration.
React starts after its JavaScript has loaded, and the browser may paint before that. If only the provider’s effect added the class, a visitor who chose dark would see a light page for a moment.
The script cannot use the schema, so it checks the stored value by hand and gets the same result as the store. colorSchemeState.inlineRead() builds the expression that reads the stored value, taking the key and shape from the @k8ordo/state definition.
Script position
<head>
<meta charset="utf-8" />
<script>(() => { … })()</script>
Ahead of every stylesheet
<link rel="stylesheet" href="/assets/index.css" />
</head>The browser runs a <script> as soon as the parser reaches it, unless a stylesheet comes before it. Then the script waits for that stylesheet to load. If the browser paints while it waits, a dark visitor sees a light page.
ColorSchemeScript goes in <head> so that it runs ahead of every stylesheet. React writes the stylesheets it hoists into <head> before the layout’s own children, and @k8ordo/framework moves the head’s inline scripts in front of them. Above is the <head> that is then sent.
On hydration React adopts the <script> element in place and does not run it again.
The hydration render
provider.tsxconst useReadsStore = (): boolean =>
useSyncExternalStore(
subscribeNever,
() => true,
() => false,
);
useEffect(() => {
if (!readsStore) return;
document.documentElement.classList.toggle(
DARK_CLASS,
scheme === 'dark',
);
}, [readsStore, scheme]);A server has neither localStorage nor matchMedia. The provider renders as if nothing were stored and the OS were light. The first render in the browser, the hydration render, reads the same values as the server.
Writing those values onto <html> would remove the class the script added. So useReadsStore returns false in the hydration render, and the effect writes no class there. It returns true from the render straight after. The store and the OS setting are also read from that render on, so the render that writes the class gets the same scheme as the script.
React’s hydration does not write <html>’s attributes back either. For markup rendered from scheme, the Switch page shows how to keep the server’s value off screen.
After hydration
After hydration, only the provider writes the class. Whenever the stored value or the OS setting changes, it applies the rule again. When scheme changes, the effect adds or removes dark on <html>.
- The visitor chooses:
setPreferenceupdates the store, and the new value shows in the next render. The write to localStorage is batched to the end of the same task. - The OS setting changes: the provider subscribes to
changeonmatchMedia('(prefers-color-scheme: dark)'). - Another tab changes it:
@k8ordo/state’s local state subscribes tostorageevents for this key, and to the onelocalStorage.clear()sends.
Inputs and result demo
What this page reads right now, and what the provider decided from it.
Inputs
- matchMedia('(prefers-color-scheme: dark)').matches
read in the browser- localStorage.getItem('k8ordo-state:color-scheme')
read in the browser- useAppState(colorSchemeState)
read in the browser
Result
- useColorScheme().preference
read in the browser- useColorScheme().scheme
read in the browser- document.documentElement.classList.contains('dark')
read in the browser
Try it
- Press the scheme switch in the header. The
localStorage.getItemanduseAppStaterows change, and so do all three result rows. - Press “Back to system”. The
localStorage.getItemrow becomes'{}', andpreferencebecomessystem. The stored value is not removed;{}stays. - Now switch your OS’s appearance setting. The
matchMediarow changes, and so do theschemeand class rows. This site’s provider is given nodefaultPreference, so the default is'system'. - Open this site in another tab and switch the scheme there. The rows in this tab change in place.
Guarantees
- When the inline script may run, ahead of the stylesheets, the page is painted after the
darkclass on<html>matches the decided scheme. - The script and the provider decide from the same stored value by the same rule. A value the schema rejects reads as nothing chosen in both.
- The hydration render writes nothing to
<html>. Hydration never removes the class the script added. - Given
themeColor, the script writes thetheme-color<meta>along with the class. Their color matches the scheme on screen after hydration too. - A visitor who chose nothing gets the default. With a
'system'default, the scheme follows changes to the OS setting while the page stays open. - localStorage is written only when
setPreferenceis called. Neither the default nor the OS setting on the first visit is stored. - A choice made in another tab, or localStorage cleared there, is reflected in this tab.
Not guaranteed
- The server does not guess the visitor’s scheme. It reads no cookie and no header, and renders from the default.
- Markup rendered from
schemekeeps the server’s value until hydration ends. - If a CSP blocks the inline script,
<html>gets nodarkclass until hydration, and notheme-color<meta>is ever written. The application puts the nonce or the hash in its policy. - Putting the script ahead of the stylesheets is up to whatever writes the HTML.
@k8ordo/frameworkdoes; elsewhere, check the HTML as sent. - Nothing checks that
ColorSchemeScriptand the provider are given the samedefaultPreference. If they differ, a visitor who chose nothing sees the scheme change after hydration. - With two providers, each writes the class. If their
defaultPreferencevalues differ, they disagree. - A direct
localStorage.setItemin the same tab is not reflected until a reload. Thestorageevent does not fire in the tab that wrote. - All it writes is the
darkclass on<html>, and thetheme-color<meta>when giventhemeColor. It sets neither the page’s colors nor the CSScolor-schemeproperty, and stores neitherprefers-contrastnorforced-colors.