Skip to content

How to understand a Zustand codebase

Zustand stores are small hooks created with `create((set, get) => ({...}))`. State and the functions that change it live together, and components subscribe by passing a selector. There's no provider, so stores can be imported anywhere, including outside React.

How to tell it's Zustand

  • zustand in package.json
  • create(...) returning a hook such as useCartStore
  • Middleware like persist, devtools or immer

Where things usually live

src/stores/ or store.ts
Store definitions, one per domain or combined slices.
src/stores/slices/
Slice creators combined into one store.

Conventions, not rules. Real projects rename and move things, so confirm against the repository.

Where to start reading

  1. Each store file, reading its state shape and actions
  2. Uses of useXStore(selector) in components
  3. Calls to getState() outside React

How a request moves through the code

  1. 1A component calls useStore(state => state.items) and subscribes to that value.
  2. 2An action calls set(...), merging new state.
  3. 3Subscribers whose selected value changed re-render.
  4. 4persist saves chosen state to storage and rehydrates it on load.

Questions to ask about the repository

  • List each store and the actions that change it.
  • Which state is persisted, and under what storage key?
  • Is store state read or written outside React components?

What trips people up

  • Selecting the whole store re-renders on every change; good code selects specific values.
  • Persisted state rehydrates asynchronously, so the first render can show default values.