# Stores and React bindings

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

Use [`createStore`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#createstore) when you want a vanilla store, including one consumed outside React. Use [`create`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#create) when you want a store already bound to a React hook. To read a vanilla store in a component, pass it to [`useStore`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#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](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/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`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#statecreator) for both creation functions to compare their return types below; see [How Zustand works](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/how-zustand-works) for initializer arguments and typed creation syntax.

[`StoreApi`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#storeapi) describes the vanilla store. [`UseBoundStore`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#useboundstore) describes a hook combined with its store API, so its type argument is the **store API type**, not the state type.

```ts title="src/counter-stores.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`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#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 title="src/App.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.

| Method | Result |
| --- | --- |
| `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](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/type-stores-and-selectors) 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`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#mutate) applies a list of middleware type transformations to a store API. [`StoreMutatorIdentifier`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#storemutatoridentifier) names the keys registered in [`StoreMutators`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#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](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/write-typed-middleware), rather than adding them to an ordinary counter store.

## Related

- [Selectors and rendering](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/selectors-and-rendering) explains how selected values control component updates.
- [Immutable state and merging](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/immutable-state-and-merging) covers object and nested-state updates.
- [Scope stores with context](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/scope-stores-with-context) shows how to give different component trees different store instances.
