Skip to main content

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 the createStore 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).
setState only exists on Store<T>, not ReadonlyStore<T>. Read-only stores are automatically recomputed when their dependencies change.

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.
You can also pass an observer object:

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:
  1. An atom is created internally using createAtom
  2. The store provides a simpler API surface with state, setState, and subscribe
  3. For mutable stores, setState calls the atom’s set method
  4. For read-only stores, the store automatically recomputes when dependencies change
From store.ts:4-29:

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

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