@k8ordo/state
React state management that reads and writes values in the URL, localStorage and cookies like useState
npm
yarn
pnpm
Copy code
npm install @k8ordo/state zodsrc/state.tsCopy code
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.tsxCopy code
const [{ q, page }, update] = useAppState(listState);
update({ page: page + 1 }, { history: 'push' });URLCopy code
/products?q=lamp&page=2Lifetime 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.tsCopy code
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.
tabpageDecrease page
Increase page
- URL
no query (all defaults)- state
{ tab: 'overview', page: 1 }
Try it
- Change
pageto0in the address bar and reload. Onlypagefalls back to1;tabstays. - Press
+besidepagea few times, then the browser’s back button.pagesteps back one at a time. - Switching
tabadds nothing to the back history. It rewrites the current entry.