Welcome to HowToShipIt — practical how-to guides for developers: code, AI tools, and servers, explained step by step.

Zustand React: The Complete Guide to State Management Without the Boilerplate (2026)

If you have ever wrapped your whole React app in a provider, written a reducer for a boolean, and then wondered why changing one value re-rendered half your tree, you already know the problem Zustand React solves. Zustand (German for “state”) is a small, fast state-management library from the pmndrs collective that turns global state into a hook: you call create(), you get a hook back, and any component can read exactly the slice it needs. No provider, no reducers, no action types.

This guide covers Zustand as it actually works in late 2026: version 5.1.0 (published 6 November 2026), zero runtime dependencies, a core of about 0.5 KB minified and gzipped, and nearly 59,000 stars on GitHub. You will build a real cart store, learn the one selector rule that decides your performance, add persistence, DevTools and Immer, type everything properly in TypeScript, and learn when not to reach for it. Every claim in this post was verified against the official docs, the npm registry, or independent 2026 guides on 22 November 2026.

What Zustand actually is (and what it isn’t)

The official README describes Zustand as “a small, fast and scalable bearbones state-management solution using simplified flux principles” with an API “based on hooks”. The mental model is one sentence: your store is a hook. You define state and the functions that change it in one object, and components subscribe to slices of that object.

Three things follow from that design:

  • No provider. The store lives in a module, independent of the React tree. Any component imports the hook and calls it. There is nothing to wrap your app in.
  • Atomic subscriptions. A component re-renders only when the slice it selected changes — not when any other part of the store changes. This is the whole performance story, and it is also where most beginners go wrong (see the selectors section below).
  • It is for client-owned state. Theme, auth session, cart contents, UI toggles, form drafts. Data that lives on a server — fetched, cached, invalidated — belongs to a server-state tool. Zustand pairs with TanStack Query; it does not replace it.

Under the hood, Zustand v5 standardises on React’s useSyncExternalStore hook, which is why v5 requires React 18 or newer and is safe with React 19’s concurrent rendering.

Zustand vs Redux Toolkit vs React Context

If you are choosing between the three, the honest comparison looks like this:

Zustand Redux Toolkit React Context
Setup One create() call Store, slices, provider Context + provider + memoisation
Boilerplate Almost none Slices and reducers Little, until you optimise
Re-render control Per-slice selectors Per-slice selectors Every consumer re-renders on any value change
DevTools Opt-in middleware Built in None
Persistence Opt-in middleware Manual Manual
Bundle ~0.5 KB min+gzip core Noticeably larger with react-redux Zero (built into React)
Best for Client state in small-to-large apps Large apps needing strict structure Truly global, rarely-changing values

Context is not a state manager — it is a dependency-injection mechanism, and any value change re-renders every consumer. That is fine for a theme string and terrible for a cart. Redux Toolkit is the right call when you need its ecosystem (RTK Query, strict action history, large-team conventions). Zustand is the right call when you want Redux-like predictability without Redux-like ceremony.

Install Zustand and create your first store

Installation is one command and no configuration. Zustand ships its own TypeScript types, and React is its only peer dependency:

npm install zustand
# or
pnpm add zustand
# or
yarn add zustand

Here is the canonical first store from the official README — a bear counter, because the library’s mascot is a bear:

import { create } from 'zustand'

const useBearStore = create((set) => ({
  bears: 0,
  increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
  removeAllBears: () => set({ bears: 0 }),
}))

Two things to notice. First, state and actions live in the same object — there is no separate actions file. Second, set merges the object you return into the existing state. You only pass the fields that change.

Bind it in a component by calling the hook with a selector:

function BearCounter() {
  const bears = useBearStore((state) => state.bears)
  return <h1>{bears} bears around here...</h1>
}

function Controls() {
  const increasePopulation = useBearStore((state) => state.increasePopulation)
  return <button onClick={increasePopulation}>Add a bear</button>
}

BearCounter re-renders only when bears changes. Controls almost never re-renders, because the increasePopulation function reference is stable. That is the whole trick — and the next section is where people break it.

Selectors: the one rule that decides your performance

Always select the exact slice your component needs. Calling the hook with no selector subscribes to the entire store, so every unrelated field change re-renders the component. It looks like working code and it is the most common Zustand performance bug:

// Bad: re-renders when ANY field in the store changes
const { bears, honey, fish } = useBearStore()

// Good: re-renders only when bears changes
const bears = useBearStore((state) => state.bears)

The trap inside the trap is selecting more than one value. A selector that returns a fresh object or array on every call produces a new reference every render, and in v5 that is not just a wasted render — it is an infinite re-render loop. The fix is useShallow:

import { useShallow } from 'zustand/react/shallow'

// Wrong: new object every render - infinite loop in v5
const { bears, honey } = useBearStore((state) => ({ bears: state.bears, honey: state.honey }))

// Correct: useShallow compares keys and values shallowly
const { bears, honey } = useBearStore(
  useShallow((state) => ({ bears: state.bears, honey: state.honey }))
)

The same rule applies to derived arrays. If a selector filters or maps a list, wrap it in useShallow or memoise the result — otherwise the new array reference re-renders the component on every store update. One more v5 change: the old second argument to the hook (a custom equality function) is gone. If you genuinely need v4-style equality behaviour, createWithEqualityFn from zustand/traditional brings it back.

Actions, async actions, and get()

Actions are plain functions inside the store, and they can be async — there are no thunks, sagas, or special async handling. The creator callback receives set and get; use get() to read current state inside an action, for example to guard against duplicate fetches:

import { create } from 'zustand'

interface CartItem {
  id: string
  name: string
  price: number
  quantity: number
}

interface CartStore {
  items: CartItem[]
  isLoading: boolean
  addItem: (product: Omit<CartItem, 'quantity'>) => void
  removeItem: (id: string) => void
  fetchCart: () => Promise<void>
}

export const useCartStore = create<CartStore>()((set, get) => ({
  items: [],
  isLoading: false,
  addItem: (product) =>
    set((state) => {
      const existing = state.items.find((item) => item.id === product.id)
      if (existing) {
        return {
          items: state.items.map((item) =>
            item.id === product.id
              ? { ...item, quantity: item.quantity + 1 }
              : item
          ),
        }
      }
      return { items: [...state.items, { ...product, quantity: 1 }] }
    }),
  removeItem: (id) =>
    set((state) => ({ items: state.items.filter((item) => item.id !== id) })),
  fetchCart: async () => {
    if (get().isLoading) return // guard: never fetch twice
    set({ isLoading: true })
    const res = await fetch('/api/cart')
    const items = await res.json()
    set({ items, isLoading: false })
  },
}))

Two details matter here. Updates must be immutable — never mutate the objects inside the store; always build new arrays and objects, as the addItem code does. And set takes an optional second argument: set(newState, true) replaces the whole state instead of merging it. That is a sharp tool — your actions live in the state object, so replacing it with an object that omits them deletes them. In v5 the types require a complete state object when the flag is true.

Derived state belongs in selectors

Do not store values you can compute. A cart total, a filtered list, an item count — all of these are selectors, not state. Storing them means keeping two sources of truth in sync, and they will drift:

// Derived: compute it where you read it
const total = useCartStore((state) =>
  state.items.reduce((sum, item) => sum + item.price * item.quantity, 0)
)

// Or define the selector once and reuse it
const selectTotal = (state: CartStore) =>
  state.items.reduce((sum, item) => sum + item.price * item.quantity, 0)

const total = useCartStore(selectTotal)

If the derivation is expensive, wrap the selector in useShallow or reach for a memoised selector. The rule is simple: state holds facts, selectors hold arithmetic.

Reading and writing state outside React

Because the store exists independently of the React tree, you can read and write it from anywhere — event handlers, services, utilities, tests — without a component in sight:

// Read the current state
const bears = useBearStore.getState().bears

// Update it from outside React
useBearStore.setState({ bears: 5 })

// Subscribe outside React (for example, to sync with analytics)
const unsubscribe = useBearStore.subscribe((state) => {
  console.log('bears changed to', state.bears)
})
unsubscribe()

If you want a store with no React dependency at all, use the vanilla API. createStore from zustand/vanilla returns a store exposing getState, setState, getInitialState and subscribe, and you can bind it to React later with the useStore hook from zustand. This is also the recommended route for framework-agnostic libraries and for tests, where a plain store is far easier to drive than a hook.

Middleware: persist, devtools, immer, and the stacking order

Zustand ships with built-in middleware that wraps your store creator. The four you will actually use are persist, devtools, immer and subscribeWithSelector. Middleware is applied from the inside out, and the recommended order is devtools outermost, then persist, then immer innermost:

import { create } from 'zustand'
import { devtools, persist, subscribeWithSelector } from 'zustand/middleware'
import { immer } from 'zustand/middleware/immer'

export const useStore = create<AppState>()(
  devtools(
    subscribeWithSelector(
      persist(
        immer((set) => ({ count: 0 })),
        { name: 'app-storage' }
      )
    ),
    { name: 'AppStore', enabled: process.env.NODE_ENV === 'development' }
  )
)

persist: state that survives a refresh

persist serialises the store to storage (localStorage by default) and rehydrates it on the next load. The name option is the storage key, and it is required:

import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'

export const useSettingsStore = create<SettingsStore>()(
  persist(
    (set) => ({
      theme: 'light',
      language: 'en',
      setTheme: (theme) => set({ theme }),
    }),
    {
      name: 'app-settings',
      storage: createJSONStorage(() => localStorage),
      // Persist only specific fields - keep tokens out
      partialize: (state) => ({ theme: state.theme, language: state.language }),
      version: 1,
      migrate: (persistedState, version) => {
        if (version === 0) return { theme: persistedState.theme, language: 'en' }
        return persistedState
      },
    }
  )
)

Three persist gotchas, all verified against current docs and guides:

  • It only stores what serialises to JSON. Functions are dropped; Map, Set and Date values need a custom storage or the replacer/reviver options of createJSONStorage. Use partialize to exclude anything that should never be saved — auth tokens especially.
  • The initial state is not written at creation. Since v4.5.5 (and in v5), the initial state is saved only after the first set. Do not expect a storage entry before the user changes something.
  • Version your persisted shape. The version + migrate pair is how old saved state (say, a cart where you renamed quantity to qty) keeps loading instead of crashing. In v5.1.0, persist also supports PromiseLike results from storage reads and migrations, and persist.rehydrate() returns a native Promise you can await.

For server-rendered apps, skipHydration defers hydration so the server and client do not disagree about the first render — see the SSR section below.

devtools: time travel without Redux

devtools connects the store to the Redux DevTools browser extension. Pass the action name as the third argument to set and it shows up in the DevTools timeline:

increment: () =>
  set((state) => ({ count: state.count + 1 }), false, 'counter/increment')

The second argument is the replace flag (false here, so set merges as usual). Gate it to development with the enabled option — DevTools wiring adds overhead you do not want in production. In v5.1.0 the middleware also gained an actionCreators option, so you can dispatch store actions directly from Redux DevTools, including nested actions.

immer: mutable syntax, immutable state

Updating nested state by hand means spreading every level. The immer middleware lets you write mutations that produce immutable updates instead. It lives in a separate import path and requires the immer package itself:

npm install immer
import { immer } from 'zustand/middleware/immer'

const useProfileStore = create<ProfileState>()(
  immer((set) => ({
    profile: { name: 'Ada', settings: { theme: 'light' } },
    setTheme: (theme) =>
      set((state) => {
        state.profile.settings.theme = theme // direct mutation, immer handles the rest
      }),
  }))
)

And subscribeWithSelector extends .subscribe() so you can watch a single slice outside React — useful for syncing state to analytics, logging, or another store.

TypeScript in Zustand v5

Zustand’s TypeScript support is genuinely good once you know the one pattern that matters: the curried create. In v5, when you use middleware with TypeScript, you write create<State>()(...) — double parentheses — so the middleware types infer correctly:

import { create } from 'zustand'

interface BearState {
  bears: number
  increasePopulation: () => void
  removeAllBears: () => void
}

export const useBearStore = create<BearState>()((set) => ({
  bears: 0,
  increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
  removeAllBears: () => set({ bears: 0 }),
}))

The generic forces the store to match the interface, so a missing action or a mistyped field is a compile error, not a runtime surprise. Three v5 breaking changes to know about if you are upgrading from v4:

  • The default import is gone: import create from 'zustand' no longer works. Use the named import, import { create } from 'zustand'.
  • React 17 support is dropped. v5 requires React 18 or newer.
  • The equality-function argument on the hook is removed. Use useShallow, or createWithEqualityFn from zustand/traditional if you need the old behaviour back.

The slices pattern: keeping large stores sane

Do not let one store file grow to 5,000 lines. Split it into slices — one creator function per domain — and combine them at the top level. Middleware is applied once, at the combined store level, not inside individual slices:

// slices/authSlice.ts
export const createAuthSlice = (set) => ({
  user: null,
  login: (user) => set({ user }),
  logout: () => set({ user: null }),
})

// slices/cartSlice.ts
export const createCartSlice = (set, get) => ({
  items: [],
  addItem: (product) => set((state) => ({ items: [...state.items, product] })),
})

// store.ts
export const useStore = create<AuthSlice & CartSlice>()((...args) => ({
  ...createAuthSlice(...args),
  ...createCartSlice(...args),
}))

Each slice stays small and testable, and a component still subscribes to exactly the fields it needs — the slices pattern changes organisation, not the subscription model.

Zustand React and server state: pair it with TanStack Query

The most common architecture mistake with Zustand is putting server data in it. API responses are not client state: they need caching, background refetching, stale-while-revalidate, and invalidation — none of which a plain store does. The standard pairing is Zustand for what your app owns (theme, auth session, cart, UI state) and TanStack Query for what the server owns. We covered the server side in detail in our TanStack Query guide: if a value came from fetch, it probably belongs there, not in a Zustand store.

Zustand React and SSR (Next.js)

Zustand works with server rendering, but the rule is simple: do not share one module-level store across requests on the server, or one user’s state leaks into another’s response. Create a fresh store per request on the server (the docs carry a per-framework guide for this), and use persist‘s skipHydration option when the persisted value must only hydrate on the client. For most apps the practical shape is: client-only stores (theme, cart, UI) in Zustand, server-fetched data in your framework’s loader or TanStack Query.

7 mistakes that trip up new Zustand users

  1. Subscribing to the whole store. useStore() with no selector re-renders on every change. Always select.
  2. Returning a fresh object or array from a selector. In v5 that is an infinite loop, not just a wasted render. Wrap grouped selections in useShallow.
  3. Mutating state directly. Always return new objects and arrays from set — or use the immer middleware and let it do the copying.
  4. Persisting things that should never be saved. Tokens, functions, and Date objects do not belong in localStorage. Use partialize and keep secrets out.
  5. Putting server data in Zustand. Fetched data needs caching and invalidation. That is TanStack Query’s job.
  6. set(newState, true) wiping your actions. The replace flag replaces the whole state object, actions included. Omit it unless you mean it.
  7. One giant store file. Split by domain with the slices pattern before the file hits a thousand lines.

When not to use Zustand

Zustand is a good default, not a universal one. Skip it when the state is local to one component (useState is the answer), when your team already standardised on Redux Toolkit and its ecosystem, or when the “state” is really a form (React Hook Form and friends handle validation, dirty tracking, and submission better than any store). And if all you need is a theme string passed down the tree, plain React Context is already there — no dependency required.

For everything in between — a cart, an auth session, a settings panel, a multi-step wizard shared across routes — Zustand React gives you a global store in one function call, with re-render behaviour you can reason about and middleware you only pay for when you use it. That is a combination no other React state library matches at this size, and it is why it keeps showing up in production apps.

Verified 22 November 2026 against the Zustand docs, the npm registry (zustand 5.1.0, published 6 November 2026), and independent 2026 guides. If you spot anything that has changed since, the docs link below is the source of truth.

Further Reading & References

Leave a Comment