@k8ordo/state

Before hydration

You will be able to read a value from an inline script before the first paint, such as a theme class that has to be on <html>. useAppState runs after hydration, which is too late for that.

On this page

storageKey and inlineRead()

src/state.ts
import { defineLocalState } from '@k8ordo/state';
import * as z from 'zod';

export const themeState = defineLocalState(
  'theme',
  z.object({ mode: z.enum(['light', 'dark']).optional() }),
);
ts
themeState.storageKey;
// 'k8ordo-state:theme'

themeState.inlineRead();
// '(()=>{try{const v=JSON.parse(localStorage.getItem("k8ordo-state:theme"));…})()'

Line 1, storageKey, is the key the store writes under in localStorage or sessionStorage. Line 4, inlineRead(), returns a JavaScript expression for an inline <script>. Evaluated in the browser, it becomes the object stored in that place.

A script with the key and the JSON shape written into it drifts the moment either changes. The expression from inlineRead() is built from the definition, so it follows every change.

Only local and session definitions have inlineRead(). In @k8ordo/framework’s server mode, the server reads a cookie state with parseCookies, so the stored value shows from the first render. For the setup, see Request and cookies.

Embedding in a <script>

src/routes/layout.tsx
import type { ReactNode } from 'react';

import { themeState } from '../state';

const applyTheme = `(() => {
  const s = ${themeState.inlineRead()};
  if (s && s.mode === 'dark') {
    document.documentElement.classList.add('dark');
  }
})();`;

export default function RootLayout({
  children,
}: {
  children: ReactNode;
}) {
  return (
    <html lang="en" suppressHydrationWarning>
      <head>
        <script>{applyTheme}</script>
      </head>
      <body>{children}</body>
    </html>
  );
}

Line 6 embeds the expression as a value. The expression is a self-invoking function. It fits on the right side of an assignment, as an argument or inside a ternary. The key is escaped, < included, so any key can be embedded.

The script changes the class of <html> before React hydrates it, so line 18 puts suppressHydrationWarning on <html>. After hydration, the store is the source of truth.

When it is null

The expression never throws. It evaluates to null when:

  • nothing is stored
  • the stored JSON is corrupt
  • the value is not an object (a number, a string, an array or null)
  • storage cannot be read
  • for a local state with a version, the stored value was written by another version

Value before the schema runs

When the script runs, no module has loaded yet. Neither the schema nor migrate runs, and what comes back is the stored value as it is. It is not the value useAppState returns, where only a field the schema rejects falls back to its default.

Treat it as untrusted and read only the fields you need, each with its own check. The example under Embedding in a <script> checks with s && s.mode === 'dark'.

Information

Note

@k8ordo/color-scheme puts a class on <html> before the first paint with inlineRead(). For a colour scheme switch, use that package.

k8ordo

React libraries that use Baseline features without holding back.