@k8ordo/color-scheme

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.ts
const 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:

  1. If the visitor chose 'light' or 'dark', that is the scheme.
  2. Otherwise the provider’s defaultPreference is used, when it is 'light' or 'dark'.
  3. 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

js
(() => {
  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

html
<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.tsx
const 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: setPreference updates 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 change on matchMedia('(prefers-color-scheme: dark)').
  • Another tab changes it: @k8ordo/state’s local state subscribes to storage events for this key, and to the one localStorage.clear() sends.
Playground

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

  1. Press the scheme switch in the header. The localStorage.getItem and useAppState rows change, and so do all three result rows.
  2. Press “Back to system”. The localStorage.getItem row becomes '{}', and preference becomes system. The stored value is not removed; {} stays.
  3. Now switch your OS’s appearance setting. The matchMedia row changes, and so do the scheme and class rows. This site’s provider is given no defaultPreference, so the default is 'system'.
  4. 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 dark class 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 the theme-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 setPreference is 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 scheme keeps the server’s value until hydration ends.
  • If a CSP blocks the inline script, <html> gets no dark class until hydration, and no theme-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/framework does; elsewhere, check the HTML as sent.
  • Nothing checks that ColorSchemeScript and the provider are given the same defaultPreference. If they differ, a visitor who chose nothing sees the scheme change after hydration.
  • With two providers, each writes the class. If their defaultPreference values differ, they disagree.
  • A direct localStorage.setItem in the same tab is not reflected until a reload. The storage event does not fire in the tab that wrote.
  • All it writes is the dark class on <html>, and the theme-color <meta> when given themeColor. It sets neither the page’s colors nor the CSS color-scheme property, and stores neither prefers-contrast nor forced-colors.
k8ordo

React libraries that use Baseline features without holding back.