A unique identifier for this store. All components that call
useStore with the same key share the same state.The initial value for the store. Objects are stored as-is. Primitives are wrapped in
{ value: T } automatically.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
AStore 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.- Metadata —
key(the key passed touseStore),scope(the scope, if provided), andfullKey(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 thescope 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
useStorewith the same key (and scope) shares the same state instance. - The
defaultValueis only used when the store is first created. Subsequent calls with the same key return the existing state regardless of thedefaultValuepassed. - 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.
useStoresupersedes useAppState, which provides a simpler tuple-based API without per-field setters or scoping. PreferuseStorefor new components.useStoremust be called inside a componentbodyfunction, not at the top level.