Skip to content
D
Documentation

Stores and React bindings

concept
3 min readUpdated

A Zustand store holds state independently of React; a React binding lets components read that state and subscribe to changes.

Use createStore when you want a vanilla store, including one consumed outside React. Use create when you want a store already bound to a React hook. To read a vanilla store in a component, pass it to useStore.

One store API, two ways to consume it

Both creation functions accept a state creator and expose the same imperative store methods. The difference is their return value:

  • createStore returns a store API object, not a hook.
  • create returns a callable hook with the store API methods attached. You do not need a context provider to use it.
  • useStore(store, selector) binds a component to an existing store; it does not create another store.
mermaid
flowchart LR
  A["State creator"] --> B["createStore: vanilla store"]
  A --> C["create: bound hook and store API"]
  B --> D["useStore: React subscription"]
  C --> E["Call the bound hook in React"]
  B --> F["Imperative reads, updates and listeners"]
  C --> F
  D --> G["Rendered state"]
  E --> G

A hook call with a selector returns the selected value and subscribes the component to it. Without a selector, it returns the whole state. An imperative getState() call reads the current state without subscribing a component.

See both bindings in React

Start from the project in the React quick start, with zustand installed. Add the following store module, then change src/App.tsx. Keep the starter's entry file, its StrictMode wrapper and its stylesheet imports.

The sample renders two independent counters. One uses a bound hook; the other uses a vanilla store through useStore. Each starts at zero, has an action button and an imperative-update button, and displays its original count.

Define the stores

Reuse one StateCreator for both creation functions to compare their return types below; see How Zustand works for initializer arguments and typed creation syntax.

StoreApi describes the vanilla store. UseBoundStore describes a hook combined with its store API, so its type argument is the store API type, not the state type.

ts
import { create } from 'zustand'
import type { StateCreator, StoreApi, UseBoundStore } from 'zustand'
import { createStore } from 'zustand/vanilla'

type CounterState = {
  count: number
  increment: () => void
}

const counterCreator: StateCreator<CounterState> = (set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
})

export const counterStore: StoreApi<CounterState> =
  createStore<CounterState>()(counterCreator)

export const useCounterStore: UseBoundStore<StoreApi<CounterState>> =
  create<CounterState>()(counterCreator)

Calling each creation function creates a separate store, even though both receive the same initializer. The updater function reads that store's current count. Its partial update shallowly merges into the state, preserving the increment action.

Read, update and subscribe

ExtractState derives the state type from a store's getState method. Use it here to type the subscription listener without redeclaring the store's shape.

tsx
import { useEffect } from 'react'
import { useStore } from 'zustand'
import type { ExtractState } from 'zustand'
import { counterStore, useCounterStore } from './counter-stores'

type CounterSnapshot = ExtractState<typeof counterStore>

export default function App() {
  const boundCount = useCounterStore((state) => state.count)
  const boundIncrement = useCounterStore((state) => state.increment)
  const vanillaCount = useStore(counterStore, (state) => state.count)
  const vanillaIncrement = useStore(counterStore, (state) => state.increment)

  useEffect(() => {
    const logChange = (
      state: CounterSnapshot,
      previous: CounterSnapshot,
    ) => {
      console.log('Count changed', previous.count, '→', state.count)
    }

    const unsubscribeBound = useCounterStore.subscribe(logChange)
    const unsubscribeVanilla = counterStore.subscribe(logChange)
    return () => {
      unsubscribeBound()
      unsubscribeVanilla()
    }
  }, [])

  return (
    <main>
      <section>
        <h2>Bound hook</h2>
        <p>Current: {boundCount}</p>
        <p>Initial: {useCounterStore.getInitialState().count}</p>
        <button onClick={boundIncrement}>Increment through action</button>
        <button onClick={() => useCounterStore.setState(
          (state) => ({ count: state.count + 10 }),
        )}>
          Add 10 through store API
        </button>
        <button onClick={() => console.log(useCounterStore.getState())}>
          Read current state in console
        </button>
      </section>
      <section>
        <h2>Vanilla store</h2>
        <p>Current: {vanillaCount}</p>
        <p>Initial: {counterStore.getInitialState().count}</p>
        <button onClick={vanillaIncrement}>Increment through action</button>
        <button onClick={() => counterStore.setState(
          (state) => ({ count: state.count + 10 }),
        )}>
          Add 10 through store API
        </button>
        <button onClick={() => console.log(counterStore.getState())}>
          Read current state in console
        </button>
      </section>
    </main>
  )
}

Click either counter's action button to increase only that counter by one. Its store-API button increases it by ten. Both routes notify the subscriptions and update the selected count on screen. The initial count remains zero. The read button logs the current state, including its action, without changing it.

The effect registers external listeners and removes them when the component unmounts. React's hook subscriptions are managed by the binding itself.

What the imperative methods mean

These methods work on both the vanilla store and the bound hook, including outside components.

MethodResult
getState()Returns the current state, including any actions stored in it. This is a read, not a subscription.
setState(partialOrUpdater)Updates synchronously. For an object update, shallowly merges top-level fields by default; returns nothing.
setState(completeState, true)Replaces the state instead of merging. See typed replacement before using it.
getInitialState()Returns the initial state captured when the store was created, not the latest state or a fresh clone. It does not reset the store.
subscribe(listener)Registers a synchronous listener receiving (state, previousState) and returns an unsubscribe function. It does not call the listener immediately.

The base subscription observes the whole store, not a selector. Notification is skipped when the proposed next state is Object.is-equal to the current state. To keep a React display reactive, use the bound hook or useStore, rather than rendering only a getState() read.

Types for extensions

The state creator's additional generic parameters describe incoming middleware mutators, outgoing middleware mutators and its return type. You can leave them at their defaults for the stores above.

Mutate applies a list of middleware type transformations to a store API. StoreMutatorIdentifier names the keys registered in StoreMutators, the interface middleware extends to describe those transformations. They describe API types; they do not create a React subscription. Use them when writing typed middleware, rather than adding them to an ordinary counter store.

Was this page helpful?

Stores and React bindings — zustand · GPT-6.1 Sol