Local reactive state
Keep framework-independent client state in a typed mutable container.
TanStack · Class
Store is TanStack Store's writable reactive container. It holds typed state, supports updates and subscriptions, and can expose optional typed actions.
Store is a writable reactive container for a value. Construct it with an initial value, read the current state through state or get(), change it with setState(), and observe changes with subscribe(); optional actions can be attached during construction.
new Store<T, TActions>(initialValue)
new Store<T, TActions>(getValue)
new Store<T, TActions>(initialValue, actionsFactory)| Name | Type | Description |
|---|---|---|
initialValue / getValue | NonFunction<T> or () => T | Initial value or value-producing function used to initialize the store. |
actionsFactory | StoreActionsFactory<T, TActions> | Factory that creates the store's optional typed actions. |
A Store<T, TActions> instance; its subscribe method returns a Subscription and setState returns void.
import { Store } from '@tanstack/store'
const count = new Store(0)
const subscription = count.subscribe((value) => {
console.log(value)
})
count.setState((value) => value + 1)
subscription.unsubscribe()Creates a writable store, observes state changes, updates the value, and removes the subscription.
Keep framework-independent client state in a typed mutable container.
Notify dependent code when a value changes.
Bundle domain-specific commands with the state they modify.
Store is a writable reactive state container. Its API exposes the current value through state or get(), changes it with setState(), and allows observers to react through subscribe().
Follow-up: How would you avoid leaving observers attached? Retain the Subscription returned by subscribe() and call its unsubscribe() method when the observer is no longer needed.
The constructor accepts an initial value and can optionally receive an actions factory. The resulting actions are exposed through the store's readonly actions property.
Follow-up: Why use an actions factory? It provides typed, store-associated commands while keeping the state update logic attached to the store instance.
setState accepts an updater and returns void. subscribe accepts either an observer or a callback and returns a Subscription that can later be unsubscribed.
Follow-up: What should a caller use when it only needs side effects for each new value? Pass a callback function directly to subscribe rather than constructing a full observer object.
ReadonlyStorecreateStoreStoreActionMapStoreActionsFactorySubscription