Global state with no selectors to write.
A store is a setup function: signals for state, computeds for derived values, plain functions for actions. Components read what they need and only that text updates, so there are no selectors, no equality functions and no provider. Patching, subscriptions, action hooks, reset and per-request SSR isolation are built in.
bun add @pyreon/store - model
- setup function, singleton per idSignals become state, functions become actions.
- selectors
- none neededReading
store.total()subscribes that one node. - server
- per-request isolationAutomatic in Pyreon's SSR renderer, via
AsyncLocalStorage. - native
- iOS and Android, experimental
defineStorecompiles to an observable singleton.
Shared state without a second framework.
No selectors, no re-render
In Zustand each component picks a slice with a selector and re-renders when it changes. Here a component reads
store.total()and the compiler binds that read to one text node. Nothing re-renders, so there is nothing to memoise.Actions you can watch
onActionsees every action call with its name and arguments, andafter/onErrorhooks around it: logging, analytics and undo without wrapping each action.Safe on a busy server
Stores are singletons by id in the browser. On the server, Pyreon's renderer gives each request its own registry through
AsyncLocalStorage, with nothing to wire, anddehydrateStores/hydrateStorescarry the state to the client.Persistence is one line
Return
useStorage('cart', [])from setup and that field is persisted and synced across tabs. Fields you don't wrap stay in memory. Nopersistmiddleware, nopartialize.
Same cart. One fewer concept per line.
A typed state shape, set callbacks that spread, and a selector in every component that reads it.
import { create } from 'zustand'
type Item = { id: string; price: number }
type Cart = { items: Item[]; add: (item: Item) => void; clear: () => void }
const useCart = create<Cart>()((set) => ({
items: [],
add: (item) => set((s) => ({ items: [...s.items, item] })),
clear: () => set({ items: [] }),
}))
function CartTotal() {
// a selector per value; this component re-renders when the result changes
const total = useCart((s) => s.items.reduce((n, i) => n + i.price, 0))
return <span>{total}</span>
}Signals, a computed and functions. The total is computed once and shared.
import { computed, defineStore, signal } from '@pyreon/store'
type Item = { id: string; price: number }
const useCart = defineStore('cart', () => {
const items = signal<Item[]>([])
const total = computed(() => items().reduce((n, i) => n + i.price, 0))
const add = (item: Item) => items.update((xs) => [...xs, item])
const clear = () => items.set([])
return { items, total, add, clear }
})
function CartTotal() {
const { store } = useCart()
return <span>{store.total()}</span> // only this text node updates
}Coming from Zustand or Jotai?
Keep the hook-shaped store, drop the selectors.
import { create } from 'zustand'
type Item = { id: string; price: number }
type Cart = { items: Item[]; add: (item: Item) => void; clear: () => void }
const useCart = create<Cart>()((set) => ({
items: [],
add: (item) => set((s) => ({ items: [...s.items, item] })),
clear: () => set({ items: [] }),
}))
function CartTotal() {
// a selector per value; this component re-renders when the result changes
const total = useCart((s) => s.items.reduce((n, i) => n + i.price, 0))
return <span>{total}</span>
}set((s) => …) becomes a signal update, derived values become computed, and a component reads fields directly. patch, subscribe, reset replace setState, subscribe and the reset pattern; persistence is useStorage instead of the persist middleware.
import { computed, defineStore, signal } from '@pyreon/store'
type Item = { id: string; price: number }
const useCart = defineStore('cart', () => {
const items = signal<Item[]>([])
const total = computed(() => items().reduce((n, i) => n + i.price, 0))
const add = (item: Item) => items.update((xs) => [...xs, item])
const clear = () => items.set([])
return { items, total, add, clear }
})
function CartTotal() {
const { store } = useCart()
return <span>{store.total()}</span> // only this text node updates
}Atoms are signals. You may not need a store at all.
import { atom, useAtomValue, useSetAtom } from 'jotai'
type Item = { id: string; price: number }
const itemsAtom = atom<Item[]>([])
const totalAtom = atom((get) => get(itemsAtom).reduce((n, i) => n + i.price, 0))
const addAtom = atom(null, (get, set, item: Item) => set(itemsAtom, [...get(itemsAtom), item]))
function CartTotal() {
const total = useAtomValue(totalAtom)
return <span>{total}</span>
}
function AddButton({ item }: { item: Item }) {
const add = useSetAtom(addAtom)
return <button onClick={() => add(item)}>Add</button>
}A primitive atom is a signal, a derived atom is a computed, a write atom is a function. Module-level signals work across components with no provider. Reach for defineStore when you want reset, subscribe, onAction or SSR isolation.
import { computed, signal } from '@pyreon/reactivity'
type Item = { id: string; price: number }
// atoms are just signals; derived atoms are computeds
const items = signal<Item[]>([])
const total = computed(() => items().reduce((n, i) => n + i.price, 0))
const add = (item: Item) => items.update((xs) => [...xs, item])
function CartTotal() {
return <span>{total()}</span>
}
function AddButton(props: { item: Item }) {
return <button onClick={() => add(props.item)}>Add</button>
}Call actions and watch the log.
A cart store. Add and remove items and watch the log: every action passes through onAction with its arguments, and every change reaches subscribe as one mutation. Hit undo to replay the previous snapshot.
Total $0 · 0 items
- Call an action.
- Each change arrives here as one mutation.
Everything a shared store needs.
defineStore(id, setup)composition stores; setup runs once, in a scope the store owns, so its effects outlive the first component.patch()an object or a function; one mutation notification however many fields change.subscribe((mutation) => …)next release events per field, plus astatesnapshot built only if you read it.onAction()name, args,afterandonErrorfor every action.reset()anddispose()back to setup values, or tear down every computed and effect the store created.defineSchemaStorenext releaseset,patch,deepPatchandupdatevalidated by Zod, Valibot, ArkType ors, with types inferred from the schema.- Plugins
addStorePluginruns for every store, and may return a cleanup fordispose(). - SSR a registry per request out of the box (swap it with
setStoreRegistryProvider),dehydrateStores/hydrateStoresacross the wire. - Store families derive the id from a parameter (
'doc:' + id) for one store per document. - Re-exports
signal,computed,effect,batchfrom the same import.
Things to build with it.
subscribe records snapshots, onAction logs each call with its arguments. Undo is a patch with the previous snapshot.
import { defineStore, signal } from '@pyreon/store'
const useDoc = defineStore('doc', () => {
const title = signal('Untitled')
const body = signal('')
const rename = (t: string) => title.set(t)
return { title, body, rename }
})
const doc = useDoc()
const history: Record<string, unknown>[] = []
// one argument: the mutation. Its state snapshot is built only if you read it.
doc.subscribe((mutation) => {
history.push(mutation.state)
})
// every action, with its arguments and result: for logging, analytics, undo
doc.onAction(({ name, args, after }) => {
after(() => console.log(`${name}(${JSON.stringify(args)})`))
})
doc.store.rename('Launch plan') // logs: rename(["Launch plan"])
doc.patch({ body: 'Ship on Monday' })
const undo = () => {
history.pop()
doc.patch(history.at(-1) ?? { title: 'Untitled', body: '' })
history.pop() // drop the snapshot the undo itself produced
}
undo()
console.log(doc.store.title(), JSON.stringify(doc.store.body())) // 'Launch plan' ''A schema store validates every object patch and types the fields from the schema.
import { defineSchemaStore } from '@pyreon/store'
import { z } from 'zod'
const useSettings = defineSchemaStore('settings', {
schema: z.object({
theme: z.enum(['light', 'dark', 'system']),
fontSize: z.number().int().min(10).max(32),
}),
initial: { theme: 'system', fontSize: 14 },
})
const settings = useSettings()
settings.patch({ fontSize: 18 }) // validated, typed from the schema
try {
settings.patch({ fontSize: 99 }) // rejected: the store keeps 18
} catch (e) {
console.log((e as Error).message)
}
console.log(settings.store.fontSize()) // 18A handful of functions and the store handle.
Every export has a reference page with its signature, an example and the mistakes people make with it.
- defineStore
- addStorePlugin
- defineSchemaStore
- store
- state
- patch
- subscribe
- onAction
- reset
- dispose
- resetStore
- resetAllStores
- setStoreRegistryProvider
- dehydrateStores
- hydrateStores
- signal
- computed
- effect
- batch
- StoreApi
- SchemaStoreApi
- StoreState
- StoreActions
- MutationInfo
Good to know before you start.
Subscribers take one argument now
subscribe((mutation) => …) reads the snapshot from mutation.state. The older (mutation, state) form is gone on main; TypeScript flags it.
Schema stores have their own function
On main, defineStore(id, { schema }) became defineSchemaStore(id, { schema, initial }), so a plain store doesn't carry the validation code. Development builds name the new function if you pass a schema to the old one.
Don't spread the store handle
{ ...api } no longer includes state. Read api.state, or destructure the methods you need (const { store, patch } = useCart()).
Outside a render, stores are per process
Each server render gets its own store registry automatically. Code that runs outside a render, like a startup script or a job, uses the process-wide registry; setStoreRegistryProvider swaps in your own.
What people ask first.
Is it faster than Zustand?
The record has a head-to-head with Zustand and Jotai, but its harness changed after that run (store ids were built inside the timed loop, PR #4142), so we don't quote it until the next measured run. The bench is packages/fundamentals/store/bench/.
Do I need a provider?
No. A store is created the first time its hook is called and shared after that. On the server, every render gets its own stores automatically.
What changed on main?
Two breaking changes, as 0.x minors: subscribers receive one mutation argument with a lazy state, and schema stores moved to defineSchemaStore. Both make plain stores cheaper: a plain store no longer ships the schema code, and a subscriber that never reads state never pays for a snapshot.
Can a store hold async work?
Yes: an action can be async. For server data with caching and refetching, use @pyreon/query and keep only client state here.
State management, minus the management.
bun add @pyreon/store