@k8ordo/state

Storage and memory

Three definitions keep state inside the browser, and they differ in how long the values last and who shares them. The difference tells you where a preference such as a view mode belongs.

On this page

localStorage

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

export const prefs = defineLocalState(
  'prefs',
  z.object({
    view: z.enum(['grid', 'table']).default('grid'),
    pageSize: z.number().default(20),
  }),
);
view-switch.tsx
const [{ view }, update] = useAppState(prefs, ['view']);

update({ view: 'table' });

defineLocalState keeps state in localStorage. useAppState reads it and update() writes it. The values stay until deleted, and every tab of the same browser sees the same ones. They are saved under the key k8ordo-state:prefs, which the definition exposes as storageKey. The saved value is the JSON of the declared fields alone, such as {"view":"table","pageSize":20}.

Keep the fields to what JSON can hold: a z.date() value shows right after the write and falls back to its default on the next load. The schema also has to read what it wrote, so a boolean is z.boolean(); z.stringbool() does not work here.

The server has no localStorage, so the server render and the hydration render show the defaults. The saved values take over after that. To render the saved value on the server, see Cookie. To apply it to <html> before the first paint, see Before hydration.

Other tabs

When another tab changes this state's values, the browser fires a storage event and the store reads the saved value again. Only the components subscribed to a key that changed re-render: when the other tab changes only pageSize, a component subscribed to ['view'] alone stays as it is.

sessionStorage

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

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

defineSessionState works like defineLocalState; only the place differs, and it is sessionStorage. The values survive a reload and are deleted when the tab closes. No other tab shares them, so the storage event fires only in other frames of the same tab.

It takes no version or migrate; see Migration.

A defineLocalState also named 'prefs' is a different state that shares no saved value. The rules for keys are on Places.

Memory

palette.ts
import { defineMemoryState } from '@k8ordo/state';

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

type Panel = { tab: 'logs' | 'network' };

export const panel = defineMemoryState<Panel>('debug-panel', {
  tab: 'logs',
});

defineMemoryState keeps state in the JavaScript runtime. Components far apart read and write the same values, and a reload puts them back to the initial ones. There is no schema: the type is inferred from the initial values. A type they cannot infer, such as a union, goes in the type argument.

update() applies each call on the spot. There is no write batching as in the other places; see Updates. The server renders the initial values.

Warning

Pitfall

Replace values through update(); never mutate them in place. Whether something changed is decided by comparing what update() received with the previous value, so a nested object mutated in place re-renders no component.

Playground

Values that survive a reload

Three definitions of the same shape that differ only in their place, each keeping one number: in localStorage, in sessionStorage and in memory.

  • localStoragek8ordo-state:storage-demo-local
    0
  • sessionStoragek8ordo-state:storage-demo-session
    0
  • Memorynot stored
    0

Try it

  1. Raise each number a few times, then reload the page. The localStorage and sessionStorage numbers stay, and the memory one goes back to 0.
  2. Copy the URL from the address bar and open it in a new tab. Only the localStorage number carries over; sessionStorage starts from 0.
  3. Raise the localStorage number in the new tab, then go back to the first one. Its number has changed to the same value.
k8ordo

React libraries that use Baseline features without holding back.