Zustand

A store as a hook, with selectors and middleware.

Builds on Build a store.

If you built the toy store in chapter 33, you've already written most of Zustand. That's not a figure of speech: Zustand's vanilla store is a closure with getState, setState, subscribe and a listener set, and its React hook is a single call to useSyncExternalStore with your selector inside getSnapshot. What Zustand adds is a nicer shape (the store is a hook), a few well-chosen middlewares, and conventions for the problems you hit once the store grows.

Redux Toolkit took the toy and added a strict rule: every change is an action through a reducer. Zustand takes the toy and keeps it loose: any function can call set. That trade, less ceremony for less enforced structure, is what this chapter is about. The sandbox runs Zustand 5.1, and the running thread moves the reading list into a Zustand store.

The problem: small shared state, big ceremony#

The reading list has a little genuinely shared client state: the list the user is curating locally, a filter, and which books are read. With context, every consumer re-renders on every change. With Redux Toolkit, you'd write a slice, configure a store, add a <Provider>, define typed hooks, and dispatch action creators. That's a lot of structure for three fields.

What you want is the toy store's directness, toggleRead(3) from anywhere, selectors so components only re-render for their slice, plus a few production features: persistence, DevTools, and a clean way to split a growing store. That's Zustand's whole pitch.

A store is a hook#

import { create } from "zustand";

const useCounter = create<{ count: number; inc: () => void }>()((set) => ({
  count: 0,
  inc: () => set((s) => ({ count: s.count + 1 })),
}));

function Counter() {
  const count = useCounter((s) => s.count); // subscribe to one field
  const inc = useCounter((s) => s.inc);
  return <button onClick={inc}>{count}</button>;
}

create takes an initializer, a function that receives set and get and returns the initial state. By convention the state includes the actions that change it, so components import one hook and get both data and behavior. create returns a hook you call with a selector, and the hook also carries the store's methods: useCounter.getState(), useCounter.setState(), useCounter.subscribe().

(The extra () in create<T>()(...) is a TypeScript workaround so you can name the state type while letting middleware types be inferred. In plain JavaScript it's just create((set) => ...).)

Here's the reading list, now in Zustand. No provider anywhere.

The reading list in a Zustand store
import { Rendered } from "guide-tools";
import { useReadingList } from "./store";

function UnreadBadge() {
  const unread = useReadingList((s) => s.books.filter((b) => !b.read).length);
  return <Rendered label="UnreadBadge">Unread: {unread}</Rendered>;
}

function ThemeLabel() {
  const theme = useReadingList((s) => s.theme);
  return <Rendered label="ThemeLabel">Theme: {theme}</Rendered>;
}

function FilterBox() {
  const filter = useReadingList((s) => s.filter);
  const setFilter = useReadingList((s) => s.setFilter);
  return <input placeholder="Filter" value={filter} onChange={(e) => setFilter(e.target.value)} />;
}

function BookList() {
  const books = useReadingList((s) => s.books);
  const filter = useReadingList((s) => s.filter);
  const toggleRead = useReadingList((s) => s.toggleRead);
  const visible = books.filter((b) => b.title.toLowerCase().includes(filter.toLowerCase()));
  return (
    <Rendered label="BookList">
      {visible.map((b) => (
        <label key={b.id} style={{ display: "block" }}>
          <input type="checkbox" checked={b.read} onChange={() => toggleRead(b.id)} /> {b.title}
        </label>
      ))}
    </Rendered>
  );
}

export default function App() {
  return (
    <>
      <UnreadBadge />
      <ThemeLabel />
      <FilterBox />
      <BookList />
      {/* Actions can be called without a hook: */}
      <button onClick={() => useReadingList.getState().flipTheme()}>Flip theme</button>
    </>
  );
}

Type in the filter: BookList re-renders, the badge and theme label don't. Toggle a book: the badge and list re-render, the theme label doesn't. Selecting the action ((s) => s.toggleRead) is free: actions are created once, so their reference never changes and never triggers a render.

Notice UnreadBadge selects a number computed from the books, not the filtered array. Derived values are computed in selectors, not stored, exactly as kinds of state recommended.

Mapping Zustand to the toy#

Here's the entire React binding in Zustand 5.1 (lightly trimmed from zustand/react):

zustand/react, simplified
function useStore(api, selector = (s) => s) {
  return React.useSyncExternalStore(
    api.subscribe,
    React.useCallback(() => selector(api.getState()), [api, selector]),
    () => selector(api.getInitialState()), // getServerSnapshot
  );
}

const create = (createState) => {
  const api = createStore(createState); // the vanilla store
  const useBoundStore = (selector) => useStore(api, selector);
  Object.assign(useBoundStore, api); // getState, setState, subscribe on the hook
  return useBoundStore;
};

Compare it with chapter 33's useStore. It's the same line, plus getServerSnapshot returning the selector applied to the initial state, which keeps server rendering and hydration consistent.

Toy storeZustand
createStore(initial)createStore(initializer) from zustand/vanilla, or create(initializer)
setState(partial | updater)set(partial | updater) inside actions, or store.setState
shallow merge of the partialthe same: one level, Object.assign({}, state, partial)
subscribe(listener)store.subscribe((state, prevState) => ...)
useStore(store, selector)useBoundStore(selector), or useStore(vanillaStore, selector)
useStoreWithEquality(..., shallow)useBoundStore(useShallow(selector))

Two details of set worth knowing:

  • It merges one level deep. set({ filter: "x" }) keeps books and theme. But for nested objects you must spread yourself: set((s) => ({ prefs: { ...s.prefs, fontSize: 16 } })). Writing set({ prefs: { fontSize: 16 } }) replaces the whole prefs object.
  • It skips no-ops by reference. If the updater returns the current state object (by Object.is), nothing is notified. And set(state, true) replaces the state instead of merging, which you rarely want because it also drops the actions unless you include them.

Selectors, useShallow, and the v5 loop#

Since the hook is the chapter 33 one-liner, it inherits the stability rule: the selector's result must be the same value when nothing relevant changed. Zustand 5 dropped the custom equality function that version 4 accepted, in favor of plain useSyncExternalStore with Object.is. So a selector that builds a new object or array every time doesn't just re-render too often, it loops.

// Each call returns a new object: Maximum update depth exceeded in Zustand 5
const { books, filter } = useReadingList((s) => ({ books: s.books, filter: s.filter }));
Why a new object from a selector loops
Rendercomponent runsgetSnapshot()React calls itselector(state)builds an objectSame as last?Object.ischanged, so re-render
Step 1 of 5

A component selects two fields as an object: useBookStore((s) => ({ books: s.books, filter: s.filter })). Zustand 5 hands that selector to useSyncExternalStore inside getSnapshot.

The fix is useShallow from zustand/react/shallow (also re-exported from zustand/shallow). It wraps your selector and remembers the previous result; if the new result is shallow-equal (same keys, each value Object.is-equal), it returns the previous object. Its implementation is the useStoreWithEquality cache you wrote in chapter 33, in about five lines.

import { useShallow } from "zustand/react/shallow";

const { books, filter } = useReadingList(useShallow((s) => ({ books: s.books, filter: s.filter })));
const [inc, reset] = useReadingList(useShallow((s) => [s.inc, s.reset]));
const titles = useReadingList(useShallow((s) => s.books.map((b) => b.title))); // array of strings: fine

That last one works because the result is an array of primitives, so shallow comparison can tell two arrays with the same titles apart from a real change. A selector that maps to new objects (s.books.map((b) => ({ ...b }))) still produces new elements every time and defeats shallow comparison; compute that inside the component from a stable slice instead, or memoize.

The guidance in order of preference:

  1. One hook call per primitive or stable reference. useStore((s) => s.filter) and useStore((s) => s.books) separately. Clearest, always correct.
  2. useShallow when you want several fields in one call, or a derived array of primitives or existing references.
  3. Never select a fresh object without useShallow, and avoid useStore() with no selector, which subscribes to the entire state and re-renders on every change.

Middleware#

Zustand middleware wraps the initializer: create(middleware(initializer, options)). Each middleware intercepts set, get or the store API to add behavior. Three cover most apps.

persist#

persist saves the state to storage on every change and rehydrates it when the store is created. The sandbox's localStorage is an in-memory shim, so watch the stored JSON below the list instead of reloading.

persist with partialize
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { useSyncExternalStore } from "react";

type Prefs = {
  theme: "light" | "dark";
  fontSize: number;
  draftNote: string; // not persisted, see partialize
  flipTheme: () => void;
  bigger: () => void;
  setDraft: (v: string) => void;
};

const usePrefs = create<Prefs>()(
  persist(
    (set) => ({
      theme: "light",
      fontSize: 14,
      draftNote: "",
      flipTheme: () => set((s) => ({ theme: s.theme === "light" ? "dark" : "light" })),
      bigger: () => set((s) => ({ fontSize: s.fontSize + 1 })),
      setDraft: (draftNote) => set({ draftNote }),
    }),
    {
      name: "prefs", // the storage key
      storage: createJSONStorage(() => localStorage),
      partialize: (s) => ({ theme: s.theme, fontSize: s.fontSize }), // only these fields
      version: 1,
    },
  ),
);

export default function App() {
  const theme = usePrefs((s) => s.theme);
  const fontSize = usePrefs((s) => s.fontSize);
  const draft = usePrefs((s) => s.draftNote);
  const { flipTheme, bigger, setDraft } = usePrefs.getState();
  // Re-read storage whenever the store changes, just to display it.
  const stored = useSyncExternalStore(usePrefs.subscribe, () => localStorage.getItem("prefs"));

  return (
    <div style={{ fontSize }}>
      <p>
        Theme {theme}, font {fontSize}px
      </p>
      <button onClick={flipTheme}>Flip theme</button> <button onClick={bigger}>Bigger</button>
      <p>
        <input placeholder="Draft note" value={draft} onChange={(e) => setDraft(e.target.value)} />
      </p>
      <p style={{ fontSize: 12 }}>
        localStorage["prefs"] = <code>{stored}</code>
      </p>
    </div>
  );
}

The stored value includes state (only the fields partialize picked) and a version. Actions are functions, so they're never serialized, and the draft is excluded on purpose: it's form state, not a preference. When you change the persisted shape, bump version and supply migrate(persistedState, version) to upgrade old data already sitting on users' machines.

Two production notes. With server rendering, the server has no localStorage, so the first render uses the initial state and rehydration updates it after hydration; for SSR apps, skipHydration: true plus a manual usePrefs.persist.rehydrate() in an effect gives you control over that moment. And usePrefs.persist.hasHydrated() tells you whether the stored values have arrived yet, which matters for async storages like IndexedDB.

devtools#

import { devtools } from "zustand/middleware";

const useReadingList = create<ReadingList>()(
  devtools(
    (set) => ({
      books: [],
      toggleRead: (id) =>
        set((s) => ({ books: s.books.map((b) => (b.id === id ? { ...b, read: !b.read } : b)) }), undefined, "books/toggleRead"),
    }),
    { name: "ReadingList" },
  ),
);

devtools connects the store to the Redux DevTools extension: every set appears as an action with the state after it, and time travel works for what you've recorded. The third argument to set names the action; without it, devtools guesses a name from the call stack or falls back to "anonymous", so name the actions you care about. Turn it off in production with the enabled option, for example enabled: process.env.NODE_ENV !== "production".

immer#

Nested updates with spreads get noisy. The immer middleware (from zustand/middleware/immer, which needs the immer package installed) lets set receive a draft, exactly like a Redux Toolkit reducer:

import { immer } from "zustand/middleware/immer";

const useReadingList = create<ReadingList>()(
  immer((set) => ({
    books: [],
    toggleRead: (id) =>
      set((s) => {
        const book = s.books.find((b) => b.id === id);
        if (book) book.read = !book.read; // a draft, not the real state
      }),
  })),
);

You can get the same effect without the middleware by calling Immer's produce yourself: set(produce((s) => { ... })).

Ordering#

When you stack middleware, devtools usually goes outermost, so it sees the final set calls from everything inside it: create(devtools(persist(immer(initializer), persistOptions))). Putting devtools inside persist or immer means it records a set that later middleware changes, which makes the DevTools log misleading.

Vanilla stores and code outside React#

Because the store is plain JavaScript, you can create it without React at all and use it anywhere: a WebSocket handler, a service worker bridge, a test, a canvas engine. createStore from zustand/vanilla returns just the API, and useStore(store, selector) from zustand connects any component to it.

A vanilla store driven from outside React
import { useEffect } from "react";
import { createStore } from "zustand/vanilla";
import { useStore } from "zustand";

type Feed = { messages: string[]; push: (m: string) => void };

// No React here. This could live in a module shared with non-React code.
const feedStore = createStore<Feed>()((set) => ({
  messages: [],
  push: (m) => set((s) => ({ messages: [...s.messages.slice(-4), m] })),
}));

// Pretend this is a socket. It talks to the store, not to components.
let n = 0;
function startFakeSocket() {
  const id = setInterval(() => feedStore.getState().push(`message ${++n}`), 700);
  return () => clearInterval(id);
}

// Plain subscription with the previous state, no rendering involved.
feedStore.subscribe((state, prev) => {
  if (state.messages.length !== prev.messages.length) console.log("feed length", state.messages.length);
});

export default function App() {
  useEffect(() => startFakeSocket(), []);
  const messages = useStore(feedStore, (s) => s.messages);
  return (
    <ul>
      {messages.map((m) => (
        <li key={m}>{m}</li>
      ))}
    </ul>
  );
}

subscribe also enables transient updates: for values that change every frame, like a pointer position driving a canvas, you can subscribe in an effect and write to a ref or the DOM directly, skipping React rendering entirely.

One store per request#

A module-level store is a singleton. That's fine in a browser and wrong on a server, where one module instance serves every request, so one user's state could render into another's page (chapter 33 covered why). For Next.js and other SSR setups, the Zustand docs recommend a vanilla store created per request and passed through context:

store-provider.tsx
"use client";
import { createContext, useContext, useState, type ReactNode } from "react";
import { createStore, type StoreApi } from "zustand/vanilla";
import { useStore } from "zustand";

type Cart = { items: string[]; add: (id: string) => void };

const createCartStore = (initial: Pick<Cart, "items">) =>
  createStore<Cart>()((set) => ({ ...initial, add: (id) => set((s) => ({ items: [...s.items, id] })) }));

const CartContext = createContext<StoreApi<Cart> | null>(null);

export function CartProvider({ initialItems, children }: { initialItems: string[]; children: ReactNode }) {
  const [store] = useState(() => createCartStore({ items: initialItems })); // once per mount
  return <CartContext value={store}>{children}</CartContext>;
}

export function useCart<T>(selector: (s: Cart) => T): T {
  const store = useContext(CartContext);
  if (!store) throw new Error("useCart must be used inside CartProvider");
  return useStore(store, selector);
}

Context carries the store reference, which never changes, so it causes no re-renders. Components still subscribe with selectors. It also lets you seed the store with server data per request.

Slices: splitting a large store#

As a store grows, you can keep one store but write it in pieces. Each slice is a function that receives set and get for the whole store and returns its part, and the store combines them with spread.

store.ts
import { create, type StateCreator } from "zustand";

type BooksSlice = { books: string[]; addBook: (t: string) => void };
type UiSlice = { theme: "light" | "dark"; flipTheme: () => void; resetAll: () => void };
type Store = BooksSlice & UiSlice;

const createBooksSlice: StateCreator<Store, [], [], BooksSlice> = (set) => ({
  books: [],
  addBook: (t) => set((s) => ({ books: [...s.books, t] })),
});

const createUiSlice: StateCreator<Store, [], [], UiSlice> = (set, get) => ({
  theme: "light",
  flipTheme: () => set({ theme: get().theme === "light" ? "dark" : "light" }),
  resetAll: () => set({ books: [], theme: "light" }), // slices can touch each other's state
});

export const useStore = create<Store>()((...a) => ({
  ...createBooksSlice(...a),
  ...createUiSlice(...a),
}));

The alternative is several small independent stores, one per concern. Zustand is happy either way. One store with slices makes cross-slice actions easy and gives DevTools one timeline; several stores keep concerns isolated and are easier to delete. Middleware like persist and devtools goes on the combined store, not on individual slices.

Zustand or Redux Toolkit?#

Both are external stores with selector subscriptions on useSyncExternalStore. The difference is structure.

ZustandRedux Toolkit
Changesany code calls setdispatch an action, a reducer decides
Boilerplatevery littleslices, store config, provider, typed hooks
Providernot needed (except per-request SSR)required
DevTools, time travelvia devtools middleware, named set callsbuilt in, every change is an action
Asyncjust async functions that call setthunks, listeners, RTK Query
Conventionsyours to defineenforced by the API

Zustand fits small to medium shared client state, teams that prefer minimal code, and stores used outside React. Redux Toolkit fits large, long-lived state where you want every change to be a named, logged, replayable event, and teams that benefit from enforced structure. "Zustand is just simpler Redux" undersells the real trade: freedom versus traceability. Choosing state tools puts the options side by side.

Pitfalls#

Check your understanding#

Fix itFix the v5 selector crash

Header selects two fields as an object and the app crashes. Fix it so it renders, the filter input works, and flipping the theme (which Header doesn't read) doesn't re-render Header.

import { create } from "zustand";
import { useRenderCount } from "guide-tools";

type State = {
  books: string[];
  filter: string;
  theme: "light" | "dark";
  setFilter: (f: string) => void;
  flipTheme: () => void;
};

const useLibrary = create<State>()((set) => ({
  books: ["Refactoring", "SICP", "Crafting Interpreters"],
  filter: "",
  theme: "light",
  setFilter: (filter) => set({ filter }),
  flipTheme: () => set((s) => ({ theme: s.theme === "light" ? "dark" : "light" })),
}));

function Header() {
  const { books, filter } = useLibrary((s) => ({ books: s.books, filter: s.filter }));
  const renders = useRenderCount();
  return (
    <p>
      {books.length} books, filter: {filter || "(none)"}, renders: <span data-testid="header-renders">{renders}</span>
    </p>
  );
}

export default function App() {
  const filter = useLibrary((s) => s.filter);
  const setFilter = useLibrary((s) => s.setFilter);
  const flipTheme = useLibrary((s) => s.flipTheme);
  return (
    <>
      <Header />
      <input aria-label="Filter" value={filter} onChange={(e) => setFilter(e.target.value)} />
      <button onClick={flipTheme}>Flip theme</button>
    </>
  );
}
Nothing logged yet.
Build itBuild the reading list store

Implement the three actions in store.ts. The checks call them from outside React through useReadingList.getState(), then look at the UI.

import { create } from "zustand";

export type Book = { id: number; title: string; read: boolean };

type ReadingList = {
  books: Book[];
  filter: string;
  addBook: (title: string) => void;
  toggleRead: (id: number) => void;
  setFilter: (filter: string) => void;
};

let nextId = 4;

export const useReadingList = create<ReadingList>()((set) => ({
  books: [
    { id: 1, title: "Refactoring", read: true },
    { id: 2, title: "SICP", read: false },
    { id: 3, title: "Crafting Interpreters", read: false },
  ],
  filter: "",
  addBook: (title) => {
    // TODO: append { id: nextId++, title, read: false }
  },
  toggleRead: (id) => {
    // TODO: flip read on the matching book, without mutating
  },
  setFilter: (filter) => {
    // TODO
  },
}));
PredictWhat does set keep?

The store's state is { user: { name: "Ada", role: "admin" }, theme: "dark" }. What is the state after each line runs, in order?

useApp.setState({ theme: "light" });
useApp.setState({ user: { name: "Grace" } });
useApp.setState((s) => ({ user: { ...s.user, role: "viewer" } }));
Quick checkOutside React

A WebSocket handler needs to append incoming messages to a Zustand store. What's the right way to do it?

Explain it out loudExplain Zustand

An interviewer asks: "How does Zustand work under the hood, and why would you pick it over Redux Toolkit?"

Interview angle

Say it in 30 seconds

Zustand is a tiny external store. Its vanilla core is a closure with getState, a setState that shallow-merges and notifies, and subscribe. create wraps it in a hook that calls useSyncExternalStore with your selector inside getSnapshot, so components re-render only when their selected value changes by Object.is, and the same hook exposes getState and setState for code outside React. Actions live in the store and call set. Because selectors must be stable, version 5 loops if you select a new object; you select primitives or wrap with useShallow. Middleware adds persistence, DevTools and Immer. It's Redux's model with far less ceremony and fewer guarantees.

How does Zustand work under the hood?

intermediate

Why does useStore((s) => ({ a: s.a, b: s.b })) crash in Zustand 5, and how do you fix it?

intermediate

A WebSocket handler, outside any component, needs to push messages into state that components display. How do you do that with Zustand, and what should you watch for?

intermediate

How do you use Zustand safely with server rendering, for example in Next.js?

senior

What do the persist, devtools and immer middlewares do, and does their order matter?

intermediate

Zustand and Redux Toolkit both sit on useSyncExternalStore. How do you choose between them?

senior

Recap#

  • Zustand is chapter 33's toy store: a vanilla closure with getState, setState and subscribe, and a hook that calls useSyncExternalStore with your selector.
  • create returns a hook that is also the store API, so actions live in the store and can be called from anywhere, including outside React.
  • set merges one level and skips same-reference updates; nested data needs spreads or the immer middleware.
  • In v5, selecting a new object or array loops. Select primitives separately or wrap with useShallow, and never call the hook without a selector.
  • persist (with partialize, version, migrate), devtools and immer cover most needs; stack devtools outermost. Use vanilla stores per request with context for SSR, and slices or several stores as the store grows.

Sources#