A signal that remembers. In every tab, after every reload.
useStorage('theme', 'light') is a signal backed by localStorage: read it with theme(), write it with theme.set(), and every open tab follows. Session storage, cookies (readable during SSR), IndexedDB and custom backends work the same way, with versioned migrations built in.
bun add @pyreon/storage - backends
- local · session · cookie · IndexedDB · memory · custom
- writes
- 10.1–29.7× fastervs Jotai
atomWithStorageand Zustandpersist; one run. - SSR
- cookies read per requestNo flash of the wrong theme or locale.
- native
- iOS and Android, experimentalPersists through the platform's own storage.
- 29.7× faster persisted writes at best (10.1× at worst) than Jotai
atomWithStorageand Zustandpersist.BENCHMARKS.md §10 storage row, overnight run 2026-11-05, bun, one run - 1.8× faster to create a persisted value (1.7× at worst).BENCHMARKS.md §10 storage row, one run
synthetic · author-run · M3 Max · record of 2026-11-05
Every result, including where we lose →Persistence without the plumbing.
It is a signal
theme()reads,theme.set()writes,theme.remove()deletes and returns to the default. Every component callinguseStorage('theme', …)gets the same signal, and every tab updates through thestorageevent.Old data upgrades itself
Give
version: 2and amigrate(old, from). A value written by last month's release, or by a tab still running it, is migrated on read. Values from before versioning arrive asfrom = 0.The right theme on the first paint
useCookiereads the request'sCookieheader during SSR. UnderrenderToStringeach request gets its own cookie signals, so concurrent users never see each other's values.Failures don't crash the page
A corrupt stored value falls back to the default, private mode degrades to memory, and a quota error reaches
onErrorwhile the UI keeps the new value.
Persisted theme, synced across tabs.
Parse, guard, listen, re-render, and remember the quota. Per key.
type Theme = 'light' | 'dark'
let theme: Theme = 'light'
try {
const raw = localStorage.getItem('theme')
if (raw) theme = JSON.parse(raw) as Theme // corrupt value? private mode?
} catch {}
window.addEventListener('storage', (e) => {
if (e.key === 'theme' && e.newValue) {
theme = JSON.parse(e.newValue) as Theme
render(theme) // and every other place that shows it
}
})
function setTheme(next: Theme) {
theme = next
localStorage.setItem('theme', JSON.stringify(next)) // quota exceeded?
render(theme)
}
setTheme('dark')A signal that is persisted, shared and synced.
import { useStorage } from '@pyreon/storage'
const theme = useStorage<'light' | 'dark'>('theme', 'light')
theme() // 'light', or whatever was saved; a corrupt value falls back to the default
theme.set('dark') // saved, and every open tab updates
theme.remove() // back to 'light', entry deletedComing from Zustand persist or Jotai atomWithStorage?
Persistence without a middleware or a store.
import { create } from 'zustand'
import { createJSONStorage, persist } from 'zustand/middleware'
type Prefs = { theme: 'light' | 'dark'; setTheme: (t: 'light' | 'dark') => void }
const usePrefs = create<Prefs>()(
persist(
(set) => ({ theme: 'light', setTheme: (theme) => set({ theme }) }),
{
name: 'prefs',
storage: createJSONStorage(() => localStorage),
version: 2,
migrate: (old, version) => (version < 2 ? { ...(old as object), theme: 'light' } : old) as Prefs,
},
),
)
// cross-tab: add your own 'storage' listener that calls usePrefs.persist.rehydrate()name becomes the key, version and migrate carry over, and cross-tab sync needs no listener. To persist part of a @pyreon/store store, return a useStorage signal from its setup instead of using partialize.
import { useStorage } from '@pyreon/storage'
type Prefs = { theme: 'light' | 'dark'; density: 'cozy' | 'compact' }
const prefs = useStorage<Prefs>('prefs', { theme: 'light', density: 'cozy' }, {
version: 2,
// runs on read for a value stored under an older version (or none: from = 0),
// including one another tab just wrote
migrate: (old, from) => (from < 2 ? { ...(old as Prefs), density: 'cozy' } : (old as Prefs)),
})
prefs.set({ ...prefs(), theme: 'dark' }) // saved; every open tab updatesThe atom is the signal.
import { useAtom } from 'jotai'
import { atomWithStorage } from 'jotai/utils'
const themeAtom = atomWithStorage<'light' | 'dark'>('theme', 'light')
function ThemeToggle() {
const [theme, setTheme] = useAtom(themeAtom)
return (
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>{theme}</button>
)
}No useAtom pair: read theme() anywhere and only that text updates. Other tabs follow through the storage event.
import { useStorage } from '@pyreon/storage'
const theme = useStorage<'light' | 'dark'>('theme', 'light') // same key → same signal
function ThemeToggle() {
return (
<button onClick={() => theme.set(theme() === 'light' ? 'dark' : 'light')}>{theme()}</button>
)
}It's really in your localStorage.
Change it, reload the page, or open this page in a second tab and watch it follow.
Only this demo's two keys are touched; the rest of this site's storage stays as it is.
(empty, defaults in use)Open this page in a second tab to see cross-tab sync.
Persisted writes 10.1× to 29.7× faster.
All three libraries write to the same in-memory storage engine, and a correctness gate checks that all three agree before anything is timed. Reads are single-digit nanoseconds everywhere; Zustand's is one nanosecond quicker.
- writewin10.1–29.7×
- createwin1.7–1.8×
- readlossZustand persist 1.5× (4 vs 3 ns, rounded)
Every place a browser can keep data.
useStoragelocalStorage, with cross-tab sync.useSessionStorageper-tab state that survives a reload.useCookiemaxAge,sameSite,secure, and SSR reads throughsetCookieSource.useIndexedDBlarge values; the signal updates at once and the write is debounced and flushed onpagehide.useMemoryStoragefor tests and SSR.createStorage({ get, set, remove })your own backend, for example encrypted at rest.version+migrateon every backend, cross-tab included.writeDebounceMscoalesce writes from a textarea; pending ones flush when the tab closes.- Custom serializers and
onErrorfor dates, maps, and quota failures. removeStorage/clearStoragecleanup helpers.
Things to build with it.
The cookie decides the server render, localStorage keeps other tabs in step, and concurrent requests each read their own cookie.
import { runWithRequestContext } from '@pyreon/runtime-server'
import { setCookieSource, useCookie, useStorage } from '@pyreon/storage'
import { AsyncLocalStorage } from 'node:async_hooks'
// server: each concurrent request reads its own Cookie header.
// runWithRequestContext (renderToString does the same) isolates the signal registry per request.
const current = new AsyncLocalStorage<Request>()
setCookieSource(() => current.getStore()?.headers.get('cookie') ?? '')
const handle = <T>(req: Request, render: () => Promise<T>) =>
current.run(req, () => runWithRequestContext(render))
// shared: the cookie decides the first paint; localStorage mirrors it for fast reads and other tabs
function useTheme() {
const cookie = useCookie<'light' | 'dark'>('theme', 'light', { maxAge: 60 * 60 * 24 * 365, sameSite: 'lax' })
const local = useStorage('theme', cookie())
const set = (next: 'light' | 'dark') => {
local.set(next)
cookie.set(next)
}
return { theme: local, set }
}Users who stored { theme } last month get { theme, density } today, on first read.
import { useStorage } from '@pyreon/storage'
type Prefs = { theme: 'light' | 'dark'; density: 'cozy' | 'compact' }
const prefs = useStorage<Prefs>('prefs', { theme: 'light', density: 'cozy' }, {
version: 2,
// runs on read for a value stored under an older version (or none: from = 0),
// including one another tab just wrote
migrate: (old, from) => (from < 2 ? { ...(old as Prefs), density: 'cozy' } : (old as Prefs)),
})
prefs.set({ ...prefs(), theme: 'dark' }) // saved; every open tab updatesFive hooks, a factory, two helpers.
Every export has a reference page with its signature, an example and the mistakes people make with it.
- useStorage
- useSessionStorage
- useCookie
- useIndexedDB
- useMemoryStorage
- createStorage
- setCookieSource
- removeStorage
- clearStorage
- StorageSignal
- StorageOptions
- CookieOptions
- IndexedDBOptions
- StorageBackend
Good to know before you start.
Not for secrets
Browser storage is readable by any script on the page. On a device, use useSecureStorage from @pyreon/hooks for tokens.
IndexedDB starts at the default
Reads are async, so the signal shows the default until the stored value arrives.
Concurrent SSR needs an accessor
Pass setCookieSource a function that reads the current request, and render inside renderToString or runWithRequestContext, which isolate the cached signals per request. A plain string is one shared slot.
One key, one set of options
Every call for a key shares one signal, so a second call's different default is ignored, with a development warning.
What people ask first.
Does it really sync between tabs?
Yes, through the browser's storage event, for localStorage-backed signals. A versioned value written by another tab is migrated before it lands. Session storage is per tab by definition.
What happens in private mode or when storage is full?
useStorage probes for write access and degrades to an in-memory value instead of throwing. A failed write calls onError; the signal keeps the new value so the UI stays consistent.
How is it measured?
One overnight run under bun, against Jotai atomWithStorage and Zustand persist writing to the same in-memory engine. We wrote it; run bun run --filter '@pyreon/storage' bench:storage.
Remember everything. Write none of the plumbing.
bun add @pyreon/storage