Skip to content
@pyreon/storage
fundamentals · persistence

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
Documentation
backends
local · session · cookie · IndexedDB · memory · custom
writes
10.1–29.7× fastervs Jotai atomWithStorage and Zustand persist; 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.
A signal that survives the reload and follows every tab Schematic: tab 1 calls theme.set('dark'); the value writes through to localStorage under the key theme, and tab 2 updates to dark. Tab 1 then reloads, comes back empty for a moment, and reads 'dark' back from storage. Later theme.set('light') travels the same path. USESTORAGE · A SIGNAL BACKED BY LOCALSTORAGE tab 1 · /settingstheme()'dark' dark modetheme()'light' light modereloading… tab 2 · /theme()'dark' dark modetheme()'light' light mode localStorage theme "dark" "light" versioned · migrations reload reads it back local · session · cookie (read during SSR) · IndexedDB · memory · custom
  • 29.7× faster persisted writes at best (10.1× at worst) than Jotai atomWithStorage and Zustand persist.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 →
why teams pick it

Persistence without the plumbing.

  1. It is a signal

    theme() reads, theme.set() writes, theme.remove() deletes and returns to the default. Every component calling useStorage('theme', …) gets the same signal, and every tab updates through the storage event.

  2. Old data upgrades itself

    Give version: 2 and a migrate(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 as from = 0.

  3. The right theme on the first paint

    useCookie reads the request's Cookie header during SSR. Under renderToString each request gets its own cookie signals, so concurrent users never see each other's values.

  4. 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 onError while the UI keeps the new value.

the difference

Persisted theme, synced across tabs.

localStorage by hand

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')
with @pyreon/storage

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 deleted
coming from

Coming from Zustand persist or Jotai atomWithStorage?

Persistence without a middleware or a store.

Zustand persist
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()
Pyreon

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 updates

The atom is the signal.

Jotai atomWithStorage
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>
  )
}
Pyreon

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>
  )
}
try it

It's really in your localStorage.

Change it, reload the page, or open this page in a second tab and watch it follow.

useStorage('pyreon-demo-theme', 'light')

Only this demo's two keys are touched; the rest of this site's storage stays as it is.

localStorage, live
(empty, defaults in use)

Open this page in a second tab to see cross-tab sync.

benchmarks

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.

vs Jotai atomWithStorage and Zustand persist · bun / JavaScriptCorePyreonrival · lower is better
  • write
    win10.1–29.7×
  • create
    win1.7–1.8×
  • read
    lossZustand persist 1.5× (4 vs 3 ns, rounded)
Apple M3 Max · record of 2026-11-05 · overnight run, one run · author-run, syntheticFull method, every loss →
what's included

Every place a browser can keep data.

  • useStorage localStorage, with cross-tab sync.
  • useSessionStorage per-tab state that survives a reload.
  • useCookie maxAge, sameSite, secure, and SSR reads through setCookieSource.
  • useIndexedDB large values; the signal updates at once and the write is debounced and flushed on pagehide.
  • useMemoryStorage for tests and SSR.
  • createStorage({ get, set, remove }) your own backend, for example encrypted at rest.
  • version + migrate on every backend, cross-tab included.
  • writeDebounceMs coalesce writes from a textarea; pending ones flush when the tab closes.
  • Custom serializers and onError for dates, maps, and quota failures.
  • removeStorage / clearStorage cleanup helpers.
recipes

Things to build with it.

A theme with no flash, on a busy server

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 }
}
Reshape stored data without losing it

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 updates
api

Five hooks, a factory, two helpers.

Every export has a reference page with its signature, an example and the mistakes people make with it.

hooks · 5
  • useStorage
  • useSessionStorage
  • useCookie
  • useIndexedDB
  • useMemoryStorage
advanced · 2
  • createStorage
  • setCookieSource
cleanup · 2
  • removeStorage
  • clearStorage
types · 5
  • StorageSignal
  • StorageOptions
  • CookieOptions
  • IndexedDBOptions
  • StorageBackend
good to know

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.

questions

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
Read the storage guide