store
Signature
store(id?: string, options?: StoreOptions): Storevaldres Create a store to hold all state
Creates a store instance that holds all atom and selector state and manages subscriptions. The store is the central hub for reading, writing, and subscribing to state.
Usage
import { atom, store } from "valdres"
const myStore = store()
const countAtom = atom(0)
Options
| Option | Type | Description |
|---|---|---|
batchUpdates | boolean | Batch sequential set() calls within a tick into one notification pass (recommended for React) |
enumerable | boolean | Retain values enumerably so store.snapshot() can list current state |
schemaValidation | boolean | Validate atom/selector values against their schema (off by default). Inherited by scoped stores. See Schema Validation. |
// Enable schema validation (e.g. outside production)
const devStore = store({ schemaValidation: import.meta.env.DEV })
Reading state
myStore.get(countAtom) // 0
Writing state
// Set directly
myStore.set(countAtom, 42)
// Update based on previous value
myStore.set(countAtom, prev => prev + 1)
Subscribing to changes
const unsub = myStore.sub(countAtom, value => {
console.log("count changed:", value)
})
// Later: stop listening
unsub()
Transactions
Batch multiple updates so subscribers only fire once:
myStore.txn(set => {
set(atomA, 1)
set(atomB, 2)
// Subscribers fire once after the transaction completes
})
Warning
Selectors that depend on atoms updated in a transaction will only recompute once, after all updates are applied. This is the intended behavior for performance.The global store
valdres exports a shared globalStore — the store that global atoms synchronize through. Import it when you need store access outside of a component (scripts, tests, workers, cross-framework code):
import { globalStore } from "valdres"
globalStore.get(myAtom)
globalStore.set(myAtom, 1)
Inside a component you normally read and write through your framework's provider/context instead — see Provider.
See also
- Provider — provide a store to your component tree
- useStore — access the current store in your components
- Schema Validation — opt-in runtime validation via the
schemaValidationoption