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
zustandinpackage.jsoncreate(...)returning a hook such asuseCartStore- Middleware like
persist,devtoolsorimmer
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
- Each store file, reading its state shape and actions
- Uses of
useXStore(selector)in components - Calls to
getState()outside React
How a request moves through the code
- A component calls
useStore(state => state.items)and subscribes to that value. - An action calls
set(...), merging new state. - Subscribers whose selected value changed re-render.
persistsaves 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.