What is a Store?
A Store is TanStack Store’s primary state management primitive. It provides a simple, type-safe way to manage mutable, reactive state in your application. Stores can be created from initial values or getter functions, and they automatically notify subscribers when their state changes.Creating Stores
There are two ways to create a store using thecreateStore function:
From an Initial Value
Create a mutable store by passing an initial value:From a Getter Function (Read-only)
Create a read-only store by passing a getter function:When you pass a function to
createStore, it returns a ReadonlyStore<T> that cannot be updated directly. This is useful for derived state.Store API
Type Signatures
Methods
setState(updater)
Updates the store’s state using an updater function. Only available on mutable stores (not read-only stores).
state / get()
Both properties return the current state value. They are functionally equivalent:
subscribe(observerOrFn)
Subscribes to changes in the store. Returns a subscription object with an unsubscribe method.
Practical Examples
Counter Store
Todo List Store
User Settings Store
How Stores Work Internally
Stores are a lightweight wrapper around atoms. When you create a store:- An atom is created internally using
createAtom - The store provides a simpler API surface with
state,setState, andsubscribe - For mutable stores,
setStatecalls the atom’ssetmethod - For read-only stores, the store automatically recomputes when dependencies change
When to Use Stores
Use Stores When
- You need simple, mutable state
- You want a high-level API
- You’re building application state
- You want built-in reactivity
Use Atoms When
- You need fine-grained control
- You’re building a library
- You need custom comparison logic
- You want lower-level primitives
Related Concepts
Atoms
Lower-level reactive primitives that power stores
Derived Stores
Create stores that automatically compute from other stores
Subscriptions
Learn how to react to state changes
Batching
Optimize performance by batching multiple updates