Zustand: the whole store in 164 lines
JuniorMiddle
Overview
Read the complete Zustand store and its React binding: a closure, a Set of listeners, a shallow merge and one call to useSyncExternalStore.
Zustand is a small state library for React, and its core is short enough to read completely: src/vanilla.ts (the store, 100 lines) and src/react.ts (the React hook, 64 lines). This tour goes through both files at the v5.1.0 tag.
You will see how a store keeps its state, what setState really does with your object, and why some selectors make React loop forever. Middleware, persist and devtools are left out.
How the pieces connect
Select a box to open the step that explains it. Dashed boxes are mentioned but not covered.
useSyncExternalStore
- create → createStore (calls)
- createStore → createStoreImpl (calls)
- create → useBoundStore (returns)
- useBoundStore → useStore (calls)
- useStore → useSyncExternalStore (calls)
- createStoreImpl → setState (creates)
- useSyncExternalStore → subscribe (subscribes)
- setState → subscribe (notifies listeners)