Zustand Patterns
Modern state management with Zustand 5.x - lightweight, TypeScript-first, no boilerplate.
Overview
- Global state without Redux complexity
- Shared state across components without prop drilling
- Persisted state with localStorage/sessionStorage
- Computed/derived state with selectors
- State that needs middleware (logging, devtools, persistence)
Upstream coverage (do not restate)
Zustand's own docs are the source for the mechanics. This skill carries only the OrchestKit delta
on top of them, in references/ork-delta.md, the rules/ files, and the checklist.
| Topic |
First-party source |
Basic store, create<State>()(), actions, async actions |
https://github.com/pmndrs/zustand/blob/main/docs/reference/apis/create.md |
| Slices pattern (splitting and combining stores) |
https://github.com/pmndrs/zustand/blob/main/docs/learn/guides/slices-pattern.md |
| Typing slices and middleware mutator tuples |
https://github.com/pmndrs/zustand/blob/main/docs/learn/guides/advanced-typescript.md |
| Immer middleware (draft mutations) |
https://github.com/pmndrs/zustand/blob/main/docs/reference/middlewares/immer.md |
persist: partialize, version, migrate, onRehydrateStorage, storage adapters |
https://github.com/pmndrs/zustand/blob/main/docs/reference/middlewares/persist.md |
devtools: action names, enabled, serialize, trace |
https://github.com/pmndrs/zustand/blob/main/docs/reference/middlewares/devtools.md |
subscribeWithSelector and non-React subscriptions |
https://github.com/pmndrs/zustand/blob/main/docs/reference/middlewares/subscribe-with-selector.md |
Selectors and useShallow re-render control |
https://github.com/pmndrs/zustand/blob/main/docs/learn/guides/prevent-rerenders-with-use-shallow.md |
v4 to v5 migration (createWithEqualityFn, React 18 floor) |
https://github.com/pmndrs/zustand/blob/main/docs/reference/migrations/migrating-to-v5.md |
| SSR and hydration |
https://github.com/pmndrs/zustand/blob/main/docs/learn/guides/ssr-and-hydration.md |
| Store testing and reset |
https://github.com/pmndrs/zustand/blob/main/docs/learn/guides/testing.md |
| Server-state ownership (use TanStack Query, not Zustand) |
https://tanstack.com/query/latest/docs/framework/react/guides/does-this-replace-client-state |
Quick Reference
// ✅ Create typed store with double-call pattern
const useStore = create<State>()((set, get) => ({ ... }));
// ✅ Use selectors for all state access
const count = useStore((s) => s.count);
// ✅ Use useShallow for multiple values (Zustand 5.x)
const { a, b } = useStore(useShallow((s) => ({ a: s.a, b: s.b })));
// ✅ Middleware order: immer → subscribeWithSelector → devtools → persist
create(persist(devtools(immer((set) => ({ ... })))))
// ❌ Never destructure entire store
const store = useStore(); // Re-renders on ANY change
// ❌ Never store server state (use TanStack Query instead)
const useStore = create((set) => ({ users: [], fetchUsers: async () => ... }));
Key Decisions
| Decision |
Option A |
Option B |
Recommendation |
| State structure |
Single store |
Multiple stores |
Slices in single store - easier cross-slice access |
| Nested updates |
Spread operator |
Immer middleware |
Immer for deeply nested state (3+ levels) |
| Persistence |
Manual localStorage |
persist middleware |
persist middleware with partialize |
| Multiple values |
Multiple selectors |
useShallow |
useShallow for 2-5 related values |
| Server state |
Zustand |
TanStack Query |
TanStack Query - Zustand for client-only state |
| DevTools |
Always on |
Conditional |
Conditional - enabled: process.env.NODE_ENV === 'development' |
Anti-Patterns & Integration
Forbidden patterns (store destructuring, derived state, server state, direct mutation) and React Query integration guidance.
Load Read("references/anti-patterns-and-integration.md") for anti-pattern examples and TanStack Query separation patterns.
Related Skills
Capability Details
store-creation
Keywords: zustand, create, store, typescript, state
Solves: Setting up type-safe Zustand stores with proper TypeScript inference
slices-pattern
Keywords: slices, modular, split, combine, StateCreator
Solves: Organizing large stores into maintainable, domain-specific slices
middleware-stack
Keywords: immer, persist, devtools, middleware, compose
Solves: Combining middleware in correct order for immutability, persistence, and debugging
selector-optimization
Keywords: selector, useShallow, re-render, performance, memoization
Solves: Preventing unnecessary re-renders with proper selector patterns
persistence-migration
Keywords: persist, localStorage, sessionStorage, migrate, version
Solves: Persisting state with schema migrations between versions
References
Load on demand with Read("references/<file>"):
| File |
Content |
ork-delta.md |
OrchestKit-specific rules: the corrected zustand/shallow label, the v5 floor, secret handling, graded slice typing |
anti-patterns-and-integration.md |
Forbidden patterns and React Query integration |
Other resources:
- Load:
Read("scripts/store-template.ts") - Production-ready store template
- Load:
Read("checklists/zustand-checklist.md") - Implementation checklist
1---2name: zustand-patterns3description: Reference for Zustand 5.x state management including slices, middleware, Immer, useShallow, persistence, selectors, and devtools integration. Documents 7 core patterns with TypeScript examples and anti-patterns. Use when building React state management with Zustand instead of Redux.4license: MIT5---6
7# Zustand Patterns
8
9Modern state management with Zustand 5.x - lightweight, TypeScript-first, no boilerplate.
10
11## Overview
12
13- Global state without Redux complexity
14- Shared state across components without prop drilling
15- Persisted state with localStorage/sessionStorage
16- Computed/derived state with selectors
17- State that needs middleware (logging, devtools, persistence)
18
19## Upstream coverage (do not restate)
20
21Zustand's own docs are the source for the mechanics. This skill carries only the OrchestKit delta
22on top of them, in `references/ork-delta.md`, the `rules/` files, and the checklist.
23
24| Topic | First-party source |
25|-------|--------------------|
26| Basic store, `create<State>()()`, actions, async actions | https://github.com/pmndrs/zustand/blob/main/docs/reference/apis/create.md |
27| Slices pattern (splitting and combining stores) | https://github.com/pmndrs/zustand/blob/main/docs/learn/guides/slices-pattern.md |
28| Typing slices and middleware mutator tuples | https://github.com/pmndrs/zustand/blob/main/docs/learn/guides/advanced-typescript.md |
29| Immer middleware (draft mutations) | https://github.com/pmndrs/zustand/blob/main/docs/reference/middlewares/immer.md |
30| persist: `partialize`, `version`, `migrate`, `onRehydrateStorage`, storage adapters | https://github.com/pmndrs/zustand/blob/main/docs/reference/middlewares/persist.md |
31| devtools: action names, `enabled`, `serialize`, `trace` | https://github.com/pmndrs/zustand/blob/main/docs/reference/middlewares/devtools.md |
32| `subscribeWithSelector` and non-React subscriptions | https://github.com/pmndrs/zustand/blob/main/docs/reference/middlewares/subscribe-with-selector.md |
33| Selectors and `useShallow` re-render control | https://github.com/pmndrs/zustand/blob/main/docs/learn/guides/prevent-rerenders-with-use-shallow.md |
34| v4 to v5 migration (`createWithEqualityFn`, React 18 floor) | https://github.com/pmndrs/zustand/blob/main/docs/reference/migrations/migrating-to-v5.md |
35| SSR and hydration | https://github.com/pmndrs/zustand/blob/main/docs/learn/guides/ssr-and-hydration.md |
36| Store testing and reset | https://github.com/pmndrs/zustand/blob/main/docs/learn/guides/testing.md |
37| Server-state ownership (use TanStack Query, not Zustand) | https://tanstack.com/query/latest/docs/framework/react/guides/does-this-replace-client-state |
38
39## Quick Reference
40
41```typescript
42// ✅ Create typed store with double-call pattern
43const useStore = create<State>()((set, get) => ({ ... }));
44
45// ✅ Use selectors for all state access
46const count = useStore((s) => s.count);
47
48// ✅ Use useShallow for multiple values (Zustand 5.x)
49const { a, b } = useStore(useShallow((s) => ({ a: s.a, b: s.b })));
50
51// ✅ Middleware order: immer → subscribeWithSelector → devtools → persist
52create(persist(devtools(immer((set) => ({ ... })))))
53
54// ❌ Never destructure entire store
55const store = useStore(); // Re-renders on ANY change
56
57// ❌ Never store server state (use TanStack Query instead)
58const useStore = create((set) => ({ users: [], fetchUsers: async () => ... }));
59```
60
61## Key Decisions
62
63| Decision | Option A | Option B | Recommendation |
64|----------|----------|----------|----------------|
65| State structure | Single store | Multiple stores | **Slices in single store** - easier cross-slice access |
66| Nested updates | Spread operator | Immer middleware | **Immer** for deeply nested state (3+ levels) |
67| Persistence | Manual localStorage | persist middleware | **persist middleware** with partialize |
68| Multiple values | Multiple selectors | useShallow | **useShallow** for 2-5 related values |
69| Server state | Zustand | TanStack Query | **TanStack Query** - Zustand for client-only state |
70| DevTools | Always on | Conditional | **Conditional** - `enabled: process.env.NODE_ENV === 'development'` |
71
72## Anti-Patterns & Integration
73
74Forbidden patterns (store destructuring, derived state, server state, direct mutation) and React Query integration guidance.
75
76Load Read("references/anti-patterns-and-integration.md") for anti-pattern examples and TanStack Query separation patterns.
77
78## Related Skills
79
80- `react-server-components-framework` - RSC hydration considerations with Zustand
81- Server state: https://tanstack.com/query/latest/docs/framework/react/guides/does-this-replace-client-state
82- Form state: https://react-hook-form.com/docs/useform
83
84## Capability Details
85
86### store-creation
87**Keywords**: zustand, create, store, typescript, state
88**Solves**: Setting up type-safe Zustand stores with proper TypeScript inference
89
90### slices-pattern
91**Keywords**: slices, modular, split, combine, StateCreator
92**Solves**: Organizing large stores into maintainable, domain-specific slices
93
94### middleware-stack
95**Keywords**: immer, persist, devtools, middleware, compose
96**Solves**: Combining middleware in correct order for immutability, persistence, and debugging
97
98### selector-optimization
99**Keywords**: selector, useShallow, re-render, performance, memoization
100**Solves**: Preventing unnecessary re-renders with proper selector patterns
101
102### persistence-migration
103**Keywords**: persist, localStorage, sessionStorage, migrate, version
104**Solves**: Persisting state with schema migrations between versions
105
106## References
107
108Load on demand with `Read("references/<file>")`:
109
110| File | Content |
111|------|---------|
112| `ork-delta.md` | OrchestKit-specific rules: the corrected `zustand/shallow` label, the v5 floor, secret handling, graded slice typing |
113| `anti-patterns-and-integration.md` | Forbidden patterns and React Query integration |
114
115Other resources:
116- Load: `Read("scripts/store-template.ts")` - Production-ready store template
117- Load: `Read("checklists/zustand-checklist.md")` - Implementation checklist