How it works · state management for React
How Zustand works
A store is a value, a way to change it, and a list of who wants to know. The whole core is about a hundred lines.
Think of it like this. A noticeboard: one sheet of paper, anyone can replace it, and everyone who signed up gets a tap on the shoulder when it changes.
- 📌 The store Holds the state, changes it, and calls everyone who subscribed. src/vanilla.ts
- ⚛️ The React hook Lets a component read one piece of the store and redraw when that piece changes. src/react.ts
- 🧱 Middleware Optional wrappers around a store: save it, log it, edit it with Immer. src/middleware
- 💾 Persist The biggest wrapper: saves the state to storage and loads it back. src/middleware/persist.ts
Follow one thing through: set({ count: 1 })
- If you passed a function, it is called with the current state to get the change.src/vanilla.ts
- If the result is the very same value as before, nothing happens.src/vanilla.ts
- Otherwise the change is merged into a copy of the state. The old object is left alone.src/vanilla.ts
- Every listener is called with the new state and the old one.src/vanilla.ts
- In React, each component runs its selector on the new state, and redraws only if its piece changed.src/react.ts
The clever bit: React already had the hard part
The React side is one call: useSyncExternalStore(api.subscribe, () => selector(api.getState())). React asks “has the thing you selected changed?” after every update, and redraws the component only when it has. So a component that reads state.count ignores every other change in the store, and Zustand needs no provider, no context and no list of dependencies.
Words you’ll meet
- store
- The one object that holds the state and the ways to change it.
- selector
- A function that picks the piece of state a component cares about.
- subscribe
- Ask to be called whenever the state changes.
- middleware
- A function that wraps a store to add a feature.
Good questions to ask next
- Why does set() make a copy instead of changing the state?
- How does a component avoid redrawing for changes it doesn’t use?
- How does persist load saved state?
Open Zustand in Bento and ask them there. It reads the project in your browser, draws its parts as a map you can press, and opens the real code behind each one.
Take Zustand apart yourself.
Free and open source. Nothing to install, no account.
More projects, taken apart
Written by hand from the code as it was on 2026-12-02 (commit e76346b). Zustand belongs to its authors; this page is an independent explanation. Spot a mistake? Tell us.