@k8ordo/state

React state management that reads and writes values in the URL, localStorage and cookies like useState

bash
npm install @k8ordo/state zod
src/state.ts
export const listState = definePageState('product-list', {
  url: z.object({
    q: z.string().default(''),
    page: z.coerce.number().int().min(1).default(1),
  }),
});
src/components/filters.tsx
const [{ q, page }, update] = useAppState(listState);

update({ page: page + 1 }, { history: 'push' });
URL
/products?q=lamp&page=2

Lifetime and reach, set by the place

definePageState keeps state in the URL and the history entry, defineLocalState in localStorage, and defineCookieState in a cookie.

Whether it survives a reload, and whether other tabs or the server can read it, follows from the place. Wherever it lives, useAppState reads and writes it.

src/state.ts
export const listState = definePageState('product-list', {
  url: z.object({
    q: z.string().default(''),
    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 density = defineCookieState(
  'density',
  z.object({
    density: z.enum(['cozy', 'compact']).default('cozy'),
  }),
);

Values typed by a zod schema

Values read back from the URL or storage pass the schema. A field that does not fit falls back to its default, and the other fields keep theirs.

update() runs the values it writes through the same schema. The TypeScript types come from the schema too, so nothing is written twice.

Playground

URL values demo

A definePageState that rewrites this page’s URL for real.

tab
page
1
URL
no query (all defaults)
state
{ tab: 'overview', page: 1 }

Try it

  1. Change page to 0 in the address bar and reload. Only page falls back to 1; tab stays.
  2. Press + beside page a few times, then the browser’s back button. page steps back one at a time.
  3. Switching tab adds nothing to the back history. It rewrites the current entry.