@k8ordo/state

Places

Where a state lives decides how long it lasts and who shares it. Knowing the seven places lets you choose where each state belongs.

On this page

Seven places

src/state.ts
import {
  defineCookieState,
  defineLocalState,
  defineMemoryState,
  definePageState,
  defineSessionState,
} from '@k8ordo/state';
import * as z from 'zod';

export const listState = definePageState('product-list', {
  url: z.object({
    page: z.coerce.number().int().min(1).default(1),
  }),
  entry: z.object({
    expanded: z.array(z.string()).default([]),
  }),
});

export const prefs = defineLocalState(
  'prefs',
  z.object({ view: z.enum(['grid', 'table']).default('grid') }),
);

export const notices = defineSessionState(
  'notices',
  z.object({ dismissed: z.array(z.string()).default([]) }),
);

export const density = defineCookieState(
  'density',
  z.object({
    density: z
      .enum(['comfortable', 'compact'])
      .default('comfortable'),
  }),
);

export const palette = defineMemoryState('command-palette', {
  open: false,
});

The function that defines a state names the place it lives in.

  • url of definePageState: the query string of the URL. Back and forward restore it, and anyone given the link sees the same values. A page that exports search in @k8ordo/framework’s server mode can read it on the server too.
  • entry of definePageState: the state of the history entry. It survives back, forward and reload. It never shows in the URL, so a shared link does not carry it.
  • hash of definePageState: the fragment of the URL, after the #. It holds one value. Back and forward restore it, and anyone given the link opens the same value. It is never sent to the server.
  • defineLocalState: localStorage. It stays until deleted, and every tab on the device sees the same values.
  • defineSessionState: sessionStorage. It survives a reload and goes when the tab closes. No other tab sees it.
  • defineCookieState: a cookie. It lasts 400 days from the last write, and every tab on the device sees the same values. It is sent with every request, so the server can read it too.
  • defineMemoryState: the JavaScript runtime. It is shared within the tab, and returns to its initial values on reload.

Whichever place a state lives in, useAppState reads and updates it.

Page scope and app scope

url and entry belong to the same history entry. They share one definition, and an update that spans both is applied at once.

Web Storage, cookies and memory belong to the whole app. Every page reads the same values. They do not belong to a page, so each has a define function of its own instead of definePageState.

Choosing a place

Go through these questions in order. The first one that fits is the place.

  1. Should someone opening the link see the same screen? Then url: a search term, filters, the page number, the selected tab. Values the server renders with go here too.
  2. Should the back button restore it, but a shared link leave it out? Then entry: an open row, an expanded panel, state that matters only while that screen is open.
  3. Is it a preference of whoever uses the device? Then localStorage or a cookie. If the server render must not show the default, as with display density, use a cookie. Otherwise localStorage is enough.
  4. Does it only need remembering while the tab is open? Then sessionStorage: a dismissed notice, a draft being written in that tab.
  5. Can it vanish on reload, and does it only need sharing between distant components? Then memory, such as whether the command palette is open.
Warning

Pitfall

Keep secrets such as sessions and tokens out of every place here. Why a cookie state can never be HttpOnly is explained on Cookie.

The key

Every definition takes a string key as its first argument. The key is the name the state is kept under.

  • definePageState: the namespace its entry values take inside the history entry’s state
  • defineLocalState and defineSessionState: the Web Storage key k8ordo-state:<key>, exposed as the definition’s storageKey
  • defineCookieState: the cookie name k8ordo-state.<key>, exposed as the definition’s cookieName
  • Every kind: the name its store is registered under in the browser

Renaming the key renames the data. The new definition cannot read values saved under the old key.

Two definitions of the same kind under one key share one store, and for localStorage, sessionStorage and cookies one stored value too. Different kinds never collide, even under the same key. Nothing in the module system can catch an overlap, so give each key a name that is unique across the app.

Information

Note

@k8ordo/color-scheme keeps its preference in a defineLocalState keyed color-scheme. In the same app, do not give a local state that key.

Where schemas go

src/state.ts
import * as z from 'zod';

export const listState = definePageState('product-list', {
  url: z.object({
    page: z.coerce.number().int().min(1),
  }),
});

A schema belongs to the places that read values back from the URL, storage or the history entry. Such values include a URL a visitor edited, Web Storage or a cookie an older schema wrote, and entry state a session restore revived. They are treated as input and pass the schema on every read.

Every field must accept a missing value. A field with neither .default() nor .optional(), like the highlighted page, makes the definition throw as the module loads. The error names the field: url fields must tolerate absence — add .default() or .optional() to: page.

Memory alone has no schema. Its values never leave the runtime and the typed update() is their only writer, so there is nothing to check again.

zod/mini

src/state.ts
import * as z from 'zod/mini';

export const listState = definePageState('product-list', {
  url: z.object({
    inStock: z._default(z.stringbool(), false),
    page: z._default(
      z.coerce.number().check(z.int(), z.gte(1)),
      1,
    ),
  }),
});

A schema written with zod or zod/mini works the same. The browser reads and writes values with the schema, so the schema ends up in the bundle. Unless the app already uses zod elsewhere, pick zod/mini: a typical definition module gzips to about a third of the size.

In zod/mini, .default() is spelled z._default() and .int().min(1) is .check(z.int(), z.gte(1)). Either way the URL holds the same values and reads them back the same way.

k8ordo

React libraries that use Baseline features without holding back.