Skip to content
@pyreon/store
fundamentals · state

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
Documentation
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, experimentaldefineStore compiles to an observable singleton.
A store action updates only the text that reads what changed A cart store defined with defineStore holds items, discount and a computed total. store.applyCoupon('TEN') sets discount; total recomputes and only the <Total> text in the page updates, from $120 to $108. The <CartBadge> reading count and the <UserMenu> reading another store stay untouched, and onAction logs the call with its name and arguments. Later store.removeCoupon() puts it back. @PYREON/STORE · NO SELECTORS defineStore('cart', () => { items = signal([…]) discount = signal(0)0.1) total = computed(…) count = computed(…) applyCoupon, … }) <Total> reads store.total()$120$108 <CartBadge> reads store.count()3 <UserMenu> another storeAda onAction … applyCoupon('TEN') removeCoupon() untouched: Badge, UserMenu a component reads store.total(); the compiler binds that one text node
why teams pick it

Shared state without a second framework.

  1. 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.

  2. Actions you can watch

    onAction sees every action call with its name and arguments, and after / onError hooks around it: logging, analytics and undo without wrapping each action.

  3. 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, and dehydrateStores / hydrateStores carry the state to the client.

  4. 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. No persist middleware, no partialize.

the difference

Same cart. One fewer concept per line.

Zustand 5 + React

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>
}
with @pyreon/store

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

Coming from Zustand or Jotai?

Keep the hook-shaped store, drop the selectors.

Zustand
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>
}
Pyreon

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.

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

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

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.

Keyboard · $129
Monitor · $349
Cable · $12

Total $0 · 0 items

onAction
  1. Call an action.
subscribe
  1. Each change arrives here as one mutation.
what's included

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 a state snapshot built only if you read it.
  • onAction() name, args, after and onError for every action.
  • reset() and dispose() back to setup values, or tear down every computed and effect the store created.
  • defineSchemaStorenext release set, patch, deepPatch and update validated by Zod, Valibot, ArkType or s, with types inferred from the schema.
  • Plugins addStorePlugin runs for every store, and may return a cleanup for dispose().
  • SSR a registry per request out of the box (swap it with setStoreRegistryProvider), dehydrateStores / hydrateStores across the wire.
  • Store families derive the id from a parameter ('doc:' + id) for one store per document.
  • Re-exports signal, computed, effect, batch from the same import.
recipes

Things to build with it.

next release
Undo and an action log

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' ''
next release
Settings that can't hold an invalid value

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()) // 18
api

A 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.

define · 2
  • defineStore
  • addStorePlugin
next release · 1
  • defineSchemaStore
on every store · 7
  • store
  • state
  • patch
  • subscribe
  • onAction
  • reset
  • dispose
lifecycle and SSR · 5
  • resetStore
  • resetAllStores
  • setStoreRegistryProvider
  • dehydrateStores
  • hydrateStores
reactivity re-exports · 4
  • signal
  • computed
  • effect
  • batch
types · 5
  • StoreApi
  • SchemaStoreApi
  • StoreState
  • StoreActions
  • MutationInfo
good to know

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.

questions

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