Skip to main content
key
string
required
A unique identifier for this store. All components that call useStore with the same key share the same state.
defaultValue
T
required
The initial value for the store. Objects are stored as-is. Primitives are wrapped in { value: T } automatically.
scope
string
An optional namespace for the store key. The resolved key becomes "scope:key". Use this to isolate stores per-instance (e.g. pass a user ID or item ID as the scope).

Returns

A Store object that combines:
  • State fields — All properties from the default value, readable directly (e.g. store.count, store.name).
  • Per-field setters — Auto-generated set<FieldName>() methods for each property (e.g. store.setCount(5)). Each setter accepts a direct value or an updater function (prev) => next.
  • set(value) — Replaces the entire store value. Accepts a direct value or an updater function (prev) => next.
  • Metadatakey (the key passed to useStore), scope (the scope, if provided), and fullKey (the resolved key "scope:key" or "key").

Usage

Basic object store

Primitive values

Primitives are wrapped in { value: T }, so the setter is setValue:

Functional updates

All setters accept an updater function for updates based on the previous value:

Scoped stores

Use the scope parameter to namespace stores per-instance:

Replacing the entire store

Shared state across components

Stores are shared by key, so separate components can read and write the same state:

Notes

  • Store state is global and persists across re-renders. Any component that calls useStore with the same key (and scope) shares the same state instance.
  • The defaultValue is only used when the store is first created. Subsequent calls with the same key return the existing state regardless of the defaultValue passed.
  • Updates to the store trigger re-renders in all components that read from it.
  • For component-local state that does not need to be shared, use useState instead.
  • useStore must be called inside a component body function, not at the top level.