Zustand Cheat Sheet
Quick reference for Zustand: creating stores, selectors, middleware, async actions, and devtools integration. Minimal React state management.
Creating Stores
| const useStore = create((set) => ({ count: 0 })) | Create a basic store with initial state |
| set({ count: 1 }) | Replace state properties (shallow merge) |
| set((state) => ({ count: state.count + 1 })) | Update state based on previous state |
| get() | Access current state outside of set (inside actions) |
| const useStore = create<MyType>()((set) => ({ ... })) | Create a typed store with TypeScript |
Selectors & Usage
| const count = useStore((state) => state.count) | Select a single value (re-renders only when count changes) |
| const { name, age } = useStore((s) => ({ name: s.name, age: s.age }), shallow) | Select multiple values with shallow equality |
| const state = useStore() | Get entire state (re-renders on any change — avoid in components) |
| const increment = useStore((s) => s.increment) | Select an action (stable reference, no re-renders) |
| useStore.getState() | Read state outside React (in callbacks, utilities) |
Middleware
| create(persist((set) => ({ ... }), { name: "my-store" })) | Persist state to localStorage automatically |
| create(devtools((set) => ({ ... }))) | Enable Redux DevTools for debugging |
| create(immer((set) => ({ ... }))) | Use Immer for mutable-style state updates |
| create(devtools(persist((set) => ({ ... }), { name: "store" }))) | Combine multiple middleware (nest them) |
| persist(..., { partialize: (s) => ({ token: s.token }) }) | Persist only selected state properties |
Async Actions & Patterns
| increment: () => set((s) => ({ count: s.count + 1 })) | Define a sync action inside the store |
| fetchData: async () => { const res = await fetch(url); set({ data: await res.json() }) } | Define an async action with fetch |
| set({ loading: true }); const data = await api(); set({ data, loading: false }) | Pattern for loading states in async actions |
| subscribe((state) => state.count, (count) => console.log(count)) | React to state changes outside components |
| useStore.setState({ count: 0 }) | Set state from outside React (imperative updates) |
DevTools & Testing
| create(devtools(fn, { name: "MyStore" })) | Name your store in Redux DevTools |
| useStore.getState() | Inspect current state in tests |
| useStore.setState({ count: 5 }) | Set state directly in tests |
| useStore.destroy() | Clean up store between tests |
| const { result } = renderHook(() => useStore((s) => s.count)) | Test selectors with renderHook |
Step-by-Step Guide
Read Guide →