React state that survives reloads, declared in one render prop and kept in localStorage or IndexedDB.
Persisting state usually means wiring a store, choosing keys, serialising, and restoring before the first render.
@practic/persist turns that into a component. Wrap the part of the UI that owns the state, and name where it
lives with two attributes. Values from localStorage are restored before the first render, so nothing flickers.
Large data, such as a graph with thousands of nodes, goes to IndexedDB with one prop. Dates, maps, sets and the
other JavaScript built-ins JSON cannot hold are converted for you, so a Date you store is a Date you read back.
Every value is stored in one documented JSON shape, so another persistence layer can read and replace it without
losing data.
npm install @practic/persist react react-dom
Or bun add, pnpm add, yarn add. The examples use @practic/bui's
inputs and buttons (npm install @practic/bui @base-ui/react), but any components work.
import { Persist } from '@practic/persist'
import { Input } from '@practic/bui'
export function Email() {
return (
<Persist.Root
data-key='my-app'
data-attr='email'
initialValue=''
>
{({ value, setValue }) => (
<Input
aria-label='Email'
placeholder='you@example.com'
value={value}
onValueChange={(next) => setValue(next)}
/>
)}
</Persist.Root>
)
}
Type something and reload the page: the value is still there.
value and setValue.usePersistedState, and set it from any
function with set.localStorage is read before the first render.storage='large-data'.Date, Map, Set, bigint, RegExp, URL, typed arrays and the like come back as
themselves, with no conversion code.Persist.Roots share a key, each with its own attribute, and stay in sync.@practic/bui. Register it once, and the widgets and theme toggle store their state here.Persist.Root| Prop | Type | Default | Description |
|---|---|---|---|
data-key |
string |
practic_bui_default |
Storage key holding the values. |
data-attr |
string |
none | Name of this value within the key. Without it, the state stays local. |
initialValue |
storable T |
(required) | Value used until one is stored. |
storage |
'large-data' |
localStorage |
Keeps the key in IndexedDB instead, for large values. |
format |
PersistFormat<T> |
none | How the value is stored across releases; see persistFormat. |
children |
({ value, setValue }) => … |
(required) | Renders the state. setValue accepts a value or an updater function. |
The value's type is inferred from initialValue, so initialValue='' gives you a string, and
initialValue={{ zoom: 1 }} an object with a numeric zoom. When the initial value cannot describe the type, such as
an empty record, an empty list or null, pass the type as an argument. In JSX, it goes right after the component
name: <Persist.Root<EventsCalendar>.
import { Persist } from '@practic/persist'
import { Button } from '@practic/bui'
type CalendarItem = {
title: string
// stored as JSON and read back as a Date
when: Date
location?: string
}
// event ids to events; an empty record says nothing about its entries, so the type is given explicitly
type EventsCalendar = Record<string, CalendarItem>
export function ListEvents() {
return (
<Persist.Root<EventsCalendar>
data-key='my-app'
data-attr='calendar'
initialValue={{}}
>
{({ value, setValue }) => (
<>
<ul>
{Object.entries(value).map(([id, event]) => (
<li key={id}>
{event.title}, {event.when.toLocaleString()}
{event.location && ` at ${event.location}`}
</li>
))}
</ul>
<Button
onClick={() =>
setValue((current) => ({
...current,
[crypto.randomUUID()]: { title: 'Stand-up', when: new Date(), location: 'Room 4' },
}))
}
>
Add a stand-up
</Button>
</>
)}
</Persist.Root>
)
}
Without the type argument, initialValue={{}} would be inferred as {}, which accepts any object and describes none
of its contents. With it, value is typed, and setValue refuses entries of the wrong shape. Types that cannot be
stored, such as functions, are refused at compile time.
Each event's when above is a Date, stored and read back as one: there is no toISOString() on the way in and no
new Date(…) on the way out. Every layer converts these values when it writes and back when it reads, at any depth:
| Stored as itself | Notes |
|---|---|
| JSON: strings, finite numbers, booleans, null | Written unchanged, so documents written before this conversion read the same. |
Date |
Kept as its ISO time. Invalid dates come back invalid. |
Map, Set |
Keys and items may be any storable value, objects and dates included. |
bigint, NaN, Infinity, -Infinity, -0 |
Numbers JSON would turn into null or 0, or refuse. |
undefined |
Kept in arrays, maps and sets. Object properties set to it are left out, as in JSON. |
RegExp, URL |
With their flags, and their full address. |
ArrayBuffer and typed arrays |
Uint8Array, Float64Array, BigInt64Array and the others. |
Functions, symbols, class instances and values that contain themselves are refused, at compile time where the type
shows it and with an error from setValue otherwise. A value reachable twice, such as one object in two arrays, comes
back as two equal copies. In storage, a converted value is an object tagged with $persist, such as
{ "$persist": "Date", "value": "2026-11-04T09:30:00.000Z" }.
Persist.EffectWrites one property of a persisted object whenever its source changes, skipping updates that would not change it. Start the source from the stored value, as the map does below. Otherwise, a reload starts it over and the effect saves that fresh value over the stored one.
import { Persist, type PersistState } from '@practic/persist'
import { Slider } from '@practic/bui'
import { useState } from 'react'
type MapView = { zoom: number }
function ZoomableMap({ view }: { view: PersistState<MapView> }) {
// read before the first render, so the map opens at the saved zoom
const [zoom, setZoom] = useState(view.value.zoom)
return (
<Persist.Effect
state={view}
valKey='zoom'
val={zoom}
>
<Slider.Root
value={zoom}
min={1}
max={10}
onValueChange={(next) => setZoom(next)}
>
<Slider.Control>
<Slider.Track>
<Slider.Indicator />
<Slider.Thumb aria-label='Map zoom' />
</Slider.Track>
</Slider.Control>
</Slider.Root>
<p>Saved zoom: {view.value.zoom}</p>
</Persist.Effect>
)
}
export function SavedZoom() {
return (
<Persist.Root
data-key='my-app'
data-attr='view'
initialValue={{ zoom: 1 }}
>
{(view) => <ZoomableMap view={view} />}
</Persist.Root>
)
}
persistCreateState and usePersistedStatePersist.Root keeps its value inside one render prop. To use a value across a component, or outside React, declare
it once with persistCreateState, at module scope. Components read it with usePersistedState, and plain
functions call its get and set, which always see the current value, whichever component changed it.
import { persistCreateState, usePersistedState } from '@practic/persist'
import { Button } from '@practic/bui'
// declared once, at module scope, so components and plain functions share the same stored value
const visits = persistCreateState<Date[]>({ key: 'my-app', attr: 'visits', initialValue: [] })
export function recordVisit() {
visits.set((current) => [...current, new Date()])
}
export function Visits() {
const { value } = usePersistedState(visits)
return (
<>
<p>
{value.length} visits, the last {value.at(-1)?.toLocaleString() ?? 'never'}
</p>
<Button onClick={recordVisit}>Record a visit</Button>
</>
)
}
persistCreateState(options) takes key, attr, initialValue, storage and format, which work like
Persist.Root's data-key, data-attr, initialValue, storage and format. Without attr, the value is kept in memory and never stored.
It returns:
| Member | Description |
|---|---|
get() |
The current value, or initialValue until one is stored. |
set(valueOrUpdater) |
Stores a value or the result of an updater, like useState's setter. |
subscribe(listener) |
Calls listener after every change to the key, and returns the function that stops it. |
ready() |
Resolves once stored values have loaded: at once for localStorage, later for IndexedDB. |
usePersistedState(state) returns { value, setValue }, as Persist.Root passes its children. It takes a declared
value, or the options directly, as in usePersistedState({ key: 'my-app', attr: 'email', initialValue: '' }). With
storage='large-data', get() returns initialValue until IndexedDB has loaded, so await ready() first when that
matters. Values set while it loads are kept, and win over the stored ones.
persistFormatStored data outlives the code that wrote it: a page from a newer release, an older one, or a hand-edited value may
be waiting in storage. Give a value a format, and it is stored with its version, read through your read, and shown
as its initialValue when read refuses it or a newer release wrote it (said once in the console). A value stored
before it had a format reads as version 0, so adding one upgrades what users already have:
import { persistCreateState, persistFormat } from '@practic/persist'
export type Zoom = { level: number }
// version 1 stores { level }; before it had a format, the zoom was stored as a bare number
export const zoomFormat = persistFormat<Zoom>({
version: 1,
read: (stored, version) => {
if (version === 0) return typeof stored === 'number' ? { level: stored } : undefined
if (typeof stored !== 'object' || stored === null || !('level' in stored)) return undefined
return typeof stored.level === 'number' ? { level: stored.level } : undefined
},
})
export const zoom = persistCreateState<Zoom>({ key: 'practic_my-app_view', attr: 'zoom', initialValue: { level: 1 }, format: zoomFormat })
read returns nothing for a value it cannot read. When a later release changes the shape, raise version and read
every earlier one in read. Keeping a stored sample of each release and reading it in a test proves it.
persistLayerMakes this package the persistence layer of components that store through the registered layer, such as
@practic/bui's, so its widgets and its colour-mode toggle keep their state here. Register it once, at module scope,
before anything renders:
import { persistRegisterLayer } from '@practic/persist/core'
import { persistLayer } from '@practic/persist'
persistRegisterLayer(persistLayer)
@practic/persist/coreThe storage contract every persistence layer shares, with no dependencies and no React, so server code can import it
too: the document format (persistReadDocument, persistWriteDocument), the conversion of values JSON cannot hold
(persistEncodeValue, persistDecodeValue, persistIsStorable), the layer registry (persistRegisterLayer,
persistGetLayer), the localStorage fallback layer (persistCreateStorageLayer), state handles over any store
(persistCreateStateIn) and storage keys (persistStorageKey, persistDefaultKey). @practic/bui builds on it, and
re-exports it from @practic/bui/persist. The registry lives on globalThis, so an app that ends up with two copies
of the package still uses one layer, and the console warns once that it loaded twice.
usePersistedStateIn(getStore, state), from @practic/persist, is the hook form of persistCreateStateIn, for a
layer of one's own.
PersistKeys, PersistStorable, PersistStorableCompatible<T>, PersistState<T> and PersistedState<T> describe
the attributes, the values a layer stores, the render-prop state, and a declared value. PersistValue and PersistCompatible<T> describe plain JSON data,
which is how those values are written.
react and react-dom 19. @practic/persist/core needs neither.{ "state": { "values": { …attributes } }, "version": 0 }. That is the envelope
zustand's persist writes, and the one the built-in fallback (persistCreateStorageLayer) writes, so switching layers keeps the
data. Values JSON cannot hold are tagged objects inside it, which both layers convert the same way.version is the format's. A document from an earlier format is upgraded as it is read
(persistDocumentMigrations, persistDocumentMigrate). One a later release wrote is neither read nor overwritten:
a page left open on an older release keeps its changes in memory and warns once, rather than replacing newer data.localStorage keys are read synchronously, so persisted values are in place before the first render.large-data keys live in IndexedDB (through idb-keyval). They load asynchronously, so initialValue shows until
they arrive.MIT © Felipe Penno. See LICENSE.