@zimezone/z-command 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/package.json +4 -1
  2. package/templates/agents/api-documenter.agent.md +161 -0
  3. package/templates/agents/architect-review.agent.md +146 -0
  4. package/templates/agents/arm-cortex-expert.agent.md +288 -0
  5. package/templates/agents/backend-architect.agent.md +309 -0
  6. package/templates/agents/backend-security-coder.agent.md +152 -0
  7. package/templates/agents/bash-pro.agent.md +285 -0
  8. package/templates/agents/c-pro.agent.md +35 -0
  9. package/templates/agents/c4-code.agent.md +320 -0
  10. package/templates/agents/c4-component.agent.md +227 -0
  11. package/templates/agents/c4-container.agent.md +248 -0
  12. package/templates/agents/c4-context.agent.md +235 -0
  13. package/templates/agents/conductor-validator.agent.md +245 -0
  14. package/templates/agents/csharp-pro.agent.md +38 -0
  15. package/templates/agents/customer-support.agent.md +148 -0
  16. package/templates/agents/database-admin.agent.md +142 -0
  17. package/templates/agents/database-architect.agent.md +238 -0
  18. package/templates/agents/database-optimizer.agent.md +144 -0
  19. package/templates/agents/debugger.agent.md +30 -0
  20. package/templates/agents/deployment-engineer.agent.md +0 -0
  21. package/templates/agents/devops-troubleshooter.agent.md +138 -0
  22. package/templates/agents/django-pro.agent.md +159 -0
  23. package/templates/agents/docs-architect.agent.md +77 -0
  24. package/templates/agents/dotnet-architect.agent.md +175 -0
  25. package/templates/agents/dx-optimizer.agent.md +63 -0
  26. package/templates/agents/elixir-pro.agent.md +38 -0
  27. package/templates/agents/error-detective.agent.md +32 -0
  28. package/templates/agents/event-sourcing-architect.agent.md +42 -0
  29. package/templates/agents/fastapi-pro.agent.md +171 -0
  30. package/templates/agents/firmware-analyst.agent.md +330 -0
  31. package/templates/agents/frontend-security-coder.agent.md +149 -0
  32. package/templates/agents/haskell-pro.agent.md +37 -0
  33. package/templates/agents/hr-pro.agent.md +105 -0
  34. package/templates/agents/incident-responder.agent.md +190 -0
  35. package/templates/agents/ios-developer.agent.md +198 -0
  36. package/templates/agents/java-pro.agent.md +156 -0
  37. package/templates/agents/javascript-pro.agent.md +35 -0
  38. package/templates/agents/julia-pro.agent.md +187 -0
  39. package/templates/agents/legal-advisor.agent.md +49 -0
  40. package/templates/agents/malware-analyst.agent.md +272 -0
  41. package/templates/agents/mermaid-expert.agent.md +39 -0
  42. package/templates/agents/minecraft-bukkit-pro.agent.md +104 -0
  43. package/templates/agents/mobile-security-coder.agent.md +163 -0
  44. package/templates/agents/monorepo-architect.agent.md +44 -0
  45. package/templates/agents/observability-engineer.agent.md +228 -0
  46. package/templates/agents/performance-engineer.agent.md +167 -0
  47. package/templates/agents/php-pro.agent.md +43 -0
  48. package/templates/agents/posix-shell-pro.agent.md +284 -0
  49. package/templates/agents/quant-analyst.agent.md +32 -0
  50. package/templates/agents/reference-builder.agent.md +167 -0
  51. package/templates/agents/reverse-engineer.agent.md +202 -0
  52. package/templates/agents/risk-manager.agent.md +41 -0
  53. package/templates/agents/ruby-pro.agent.md +35 -0
  54. package/templates/agents/rust-pro.agent.md +156 -0
  55. package/templates/agents/sales-automator.agent.md +35 -0
  56. package/templates/agents/scala-pro.agent.md +60 -0
  57. package/templates/agents/search-specialist.agent.md +59 -0
  58. package/templates/agents/security-auditor.agent.md +138 -0
  59. package/templates/agents/seo-authority-builder.agent.md +116 -0
  60. package/templates/agents/seo-cannibalization-detector.agent.md +103 -0
  61. package/templates/agents/seo-content-auditor.agent.md +63 -0
  62. package/templates/agents/seo-content-planner.agent.md +88 -0
  63. package/templates/agents/seo-content-refresher.agent.md +98 -0
  64. package/templates/agents/seo-content-writer.agent.md +76 -0
  65. package/templates/agents/seo-keyword-strategist.agent.md +75 -0
  66. package/templates/agents/seo-meta-optimizer.agent.md +72 -0
  67. package/templates/agents/seo-snippet-hunter.agent.md +94 -0
  68. package/templates/agents/seo-structure-architect.agent.md +88 -0
  69. package/templates/agents/service-mesh-expert.agent.md +41 -0
  70. package/templates/agents/sql-pro.agent.md +146 -0
  71. package/templates/agents/tdd-orchestrator.agent.md +183 -0
  72. package/templates/agents/temporal-python-pro.agent.md +349 -0
  73. package/templates/agents/terraform-specialist.agent.md +137 -0
  74. package/templates/agents/test-automator.agent.md +203 -0
  75. package/templates/agents/threat-modeling-expert.agent.md +44 -0
  76. package/templates/agents/tutorial-engineer.agent.md +118 -0
  77. package/templates/agents/ui-ux-designer.agent.md +188 -0
  78. package/templates/agents/ui-visual-validator.agent.md +192 -0
  79. package/templates/agents/vector-database-engineer.agent.md +43 -0
  80. package/templates/skills/angular-migration/SKILL.md +410 -0
  81. package/templates/skills/api-design-principles/SKILL.md +528 -0
  82. package/templates/skills/api-design-principles/assets/api-design-checklist.md +155 -0
  83. package/templates/skills/api-design-principles/assets/rest-api-template.py +182 -0
  84. package/templates/skills/api-design-principles/references/graphql-schema-design.md +583 -0
  85. package/templates/skills/api-design-principles/references/rest-best-practices.md +408 -0
  86. package/templates/skills/architecture-decision-records/SKILL.md +428 -0
  87. package/templates/skills/architecture-patterns/SKILL.md +494 -0
  88. package/templates/skills/async-python-patterns/SKILL.md +694 -0
  89. package/templates/skills/auth-implementation-patterns/SKILL.md +634 -0
  90. package/templates/skills/changelog-automation/SKILL.md +552 -0
  91. package/templates/skills/code-review-excellence/SKILL.md +520 -0
  92. package/templates/skills/competitive-landscape/SKILL.md +479 -0
  93. package/templates/skills/context-driven-development/SKILL.md +385 -0
  94. package/templates/skills/cost-optimization/SKILL.md +274 -0
  95. package/templates/skills/cqrs-implementation/SKILL.md +554 -0
  96. package/templates/skills/data-quality-frameworks/SKILL.md +587 -0
  97. package/templates/skills/data-storytelling/SKILL.md +453 -0
  98. package/templates/skills/database-migration/SKILL.md +424 -0
  99. package/templates/skills/dbt-transformation-patterns/SKILL.md +561 -0
  100. package/templates/skills/debugging-strategies/SKILL.md +527 -0
  101. package/templates/skills/defi-protocol-templates/SKILL.md +454 -0
  102. package/templates/skills/dependency-upgrade/SKILL.md +409 -0
  103. package/templates/skills/deployment-pipeline-design/SKILL.md +359 -0
  104. package/templates/skills/distributed-tracing/SKILL.md +438 -0
  105. package/templates/skills/dotnet-backend-patterns/SKILL.md +815 -0
  106. package/templates/skills/dotnet-backend-patterns/assets/repository-template.cs +523 -0
  107. package/templates/skills/dotnet-backend-patterns/assets/service-template.cs +336 -0
  108. package/templates/skills/dotnet-backend-patterns/references/dapper-patterns.md +544 -0
  109. package/templates/skills/dotnet-backend-patterns/references/ef-core-best-practices.md +355 -0
  110. package/templates/skills/e2e-testing-patterns/SKILL.md +547 -0
  111. package/templates/skills/employment-contract-templates/SKILL.md +507 -0
  112. package/templates/skills/error-handling-patterns/SKILL.md +636 -0
  113. package/templates/skills/event-store-design/SKILL.md +437 -0
  114. package/templates/skills/fastapi-templates/SKILL.md +567 -0
  115. package/templates/skills/git-advanced-workflows/SKILL.md +400 -0
  116. package/templates/skills/github-actions-templates/SKILL.md +333 -0
  117. package/templates/skills/go-concurrency-patterns/SKILL.md +655 -0
  118. package/templates/skills/grafana-dashboards/SKILL.md +369 -0
  119. package/templates/skills/helm-chart-scaffolding/SKILL.md +544 -0
  120. package/templates/skills/helm-chart-scaffolding/assets/Chart.yaml.template +42 -0
  121. package/templates/skills/helm-chart-scaffolding/assets/values.yaml.template +185 -0
  122. package/templates/skills/helm-chart-scaffolding/references/chart-structure.md +500 -0
  123. package/templates/skills/helm-chart-scaffolding/scripts/validate-chart.sh +244 -0
  124. package/templates/skills/javascript-testing-patterns/SKILL.md +1025 -0
  125. package/templates/skills/langchain-architecture/SKILL.md +338 -0
  126. package/templates/skills/llm-evaluation/SKILL.md +471 -0
  127. package/templates/skills/microservices-patterns/SKILL.md +595 -0
  128. package/templates/skills/modern-javascript-patterns/SKILL.md +911 -0
  129. package/templates/skills/monorepo-management/SKILL.md +622 -0
  130. package/templates/skills/nextjs-app-router-patterns/SKILL.md +544 -0
  131. package/templates/skills/nodejs-backend-patterns/SKILL.md +1020 -0
  132. package/templates/skills/nx-workspace-patterns/SKILL.md +452 -0
  133. package/templates/skills/openapi-spec-generation/SKILL.md +1028 -0
  134. package/templates/skills/paypal-integration/SKILL.md +467 -0
  135. package/templates/skills/pci-compliance/SKILL.md +466 -0
  136. package/templates/skills/postgresql/SKILL.md +204 -0
  137. package/templates/skills/projection-patterns/SKILL.md +490 -0
  138. package/templates/skills/prometheus-configuration/SKILL.md +392 -0
  139. package/templates/skills/prompt-engineering-patterns/SKILL.md +201 -0
  140. package/templates/skills/prompt-engineering-patterns/assets/few-shot-examples.json +106 -0
  141. package/templates/skills/prompt-engineering-patterns/assets/prompt-template-library.md +246 -0
  142. package/templates/skills/prompt-engineering-patterns/references/chain-of-thought.md +399 -0
  143. package/templates/skills/prompt-engineering-patterns/references/few-shot-learning.md +369 -0
  144. package/templates/skills/prompt-engineering-patterns/references/prompt-optimization.md +414 -0
  145. package/templates/skills/prompt-engineering-patterns/references/prompt-templates.md +470 -0
  146. package/templates/skills/prompt-engineering-patterns/references/system-prompts.md +189 -0
  147. package/templates/skills/prompt-engineering-patterns/scripts/optimize-prompt.py +279 -0
  148. package/templates/skills/python-packaging/SKILL.md +870 -0
  149. package/templates/skills/python-performance-optimization/SKILL.md +869 -0
  150. package/templates/skills/python-testing-patterns/SKILL.md +907 -0
  151. package/templates/skills/rag-implementation/SKILL.md +403 -0
  152. package/templates/skills/react-modernization/SKILL.md +513 -0
  153. package/templates/skills/react-native-architecture/SKILL.md +671 -0
  154. package/templates/skills/react-state-management/SKILL.md +429 -0
  155. package/templates/skills/risk-metrics-calculation/SKILL.md +555 -0
  156. package/templates/skills/rust-async-patterns/SKILL.md +517 -0
  157. package/templates/skills/secrets-management/SKILL.md +346 -0
  158. package/templates/skills/security-requirement-extraction/SKILL.md +677 -0
  159. package/templates/skills/shellcheck-configuration/SKILL.md +454 -0
  160. package/templates/skills/similarity-search-patterns/SKILL.md +558 -0
  161. package/templates/skills/slo-implementation/SKILL.md +329 -0
  162. package/templates/skills/sql-optimization-patterns/SKILL.md +493 -0
  163. package/templates/skills/stripe-integration/SKILL.md +442 -0
  164. package/templates/skills/tailwind-design-system/SKILL.md +666 -0
  165. package/templates/skills/temporal-python-testing/SKILL.md +158 -0
  166. package/templates/skills/temporal-python-testing/resources/integration-testing.md +455 -0
  167. package/templates/skills/temporal-python-testing/resources/local-setup.md +553 -0
  168. package/templates/skills/temporal-python-testing/resources/replay-testing.md +462 -0
  169. package/templates/skills/temporal-python-testing/resources/unit-testing.md +328 -0
  170. package/templates/skills/terraform-module-library/SKILL.md +249 -0
  171. package/templates/skills/terraform-module-library/references/aws-modules.md +63 -0
  172. package/templates/skills/threat-mitigation-mapping/SKILL.md +745 -0
  173. package/templates/skills/track-management/SKILL.md +593 -0
  174. package/templates/skills/typescript-advanced-types/SKILL.md +717 -0
  175. package/templates/skills/uv-package-manager/SKILL.md +831 -0
  176. package/templates/skills/vector-index-tuning/SKILL.md +521 -0
  177. package/templates/skills/wcag-audit-patterns/SKILL.md +555 -0
  178. package/templates/skills/workflow-orchestration-patterns/SKILL.md +316 -0
  179. package/templates/skills/workflow-patterns/SKILL.md +623 -0
  180. package/templates/agents/game-developer.agent.md +0 -57
  181. package/templates/agents/kubernetes-specialist.agent.md +0 -56
  182. package/templates/agents/market-researcher.agent.md +0 -47
@@ -0,0 +1,429 @@
1
+ ---
2
+ name: react-state-management
3
+ description: Master modern React state management with Redux Toolkit, Zustand, Jotai, and React Query. Use when setting up global state, managing server state, or choosing between state management solutions.
4
+ ---
5
+
6
+ # React State Management
7
+
8
+ Comprehensive guide to modern React state management patterns, from local component state to global stores and server state synchronization.
9
+
10
+ ## When to Use This Skill
11
+
12
+ - Setting up global state management in a React app
13
+ - Choosing between Redux Toolkit, Zustand, or Jotai
14
+ - Managing server state with React Query or SWR
15
+ - Implementing optimistic updates
16
+ - Debugging state-related issues
17
+ - Migrating from legacy Redux to modern patterns
18
+
19
+ ## Core Concepts
20
+
21
+ ### 1. State Categories
22
+
23
+ | Type | Description | Solutions |
24
+ |------|-------------|-----------|
25
+ | **Local State** | Component-specific, UI state | useState, useReducer |
26
+ | **Global State** | Shared across components | Redux Toolkit, Zustand, Jotai |
27
+ | **Server State** | Remote data, caching | React Query, SWR, RTK Query |
28
+ | **URL State** | Route parameters, search | React Router, nuqs |
29
+ | **Form State** | Input values, validation | React Hook Form, Formik |
30
+
31
+ ### 2. Selection Criteria
32
+
33
+ ```
34
+ Small app, simple state → Zustand or Jotai
35
+ Large app, complex state → Redux Toolkit
36
+ Heavy server interaction → React Query + light client state
37
+ Atomic/granular updates → Jotai
38
+ ```
39
+
40
+ ## Quick Start
41
+
42
+ ### Zustand (Simplest)
43
+
44
+ ```typescript
45
+ // store/useStore.ts
46
+ import { create } from 'zustand'
47
+ import { devtools, persist } from 'zustand/middleware'
48
+
49
+ interface AppState {
50
+ user: User | null
51
+ theme: 'light' | 'dark'
52
+ setUser: (user: User | null) => void
53
+ toggleTheme: () => void
54
+ }
55
+
56
+ export const useStore = create<AppState>()(
57
+ devtools(
58
+ persist(
59
+ (set) => ({
60
+ user: null,
61
+ theme: 'light',
62
+ setUser: (user) => set({ user }),
63
+ toggleTheme: () => set((state) => ({
64
+ theme: state.theme === 'light' ? 'dark' : 'light'
65
+ })),
66
+ }),
67
+ { name: 'app-storage' }
68
+ )
69
+ )
70
+ )
71
+
72
+ // Usage in component
73
+ function Header() {
74
+ const { user, theme, toggleTheme } = useStore()
75
+ return (
76
+ <header className={theme}>
77
+ {user?.name}
78
+ <button onClick={toggleTheme}>Toggle Theme</button>
79
+ </header>
80
+ )
81
+ }
82
+ ```
83
+
84
+ ## Patterns
85
+
86
+ ### Pattern 1: Redux Toolkit with TypeScript
87
+
88
+ ```typescript
89
+ // store/index.ts
90
+ import { configureStore } from '@reduxjs/toolkit'
91
+ import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'
92
+ import userReducer from './slices/userSlice'
93
+ import cartReducer from './slices/cartSlice'
94
+
95
+ export const store = configureStore({
96
+ reducer: {
97
+ user: userReducer,
98
+ cart: cartReducer,
99
+ },
100
+ middleware: (getDefaultMiddleware) =>
101
+ getDefaultMiddleware({
102
+ serializableCheck: {
103
+ ignoredActions: ['persist/PERSIST'],
104
+ },
105
+ }),
106
+ })
107
+
108
+ export type RootState = ReturnType<typeof store.getState>
109
+ export type AppDispatch = typeof store.dispatch
110
+
111
+ // Typed hooks
112
+ export const useAppDispatch: () => AppDispatch = useDispatch
113
+ export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
114
+ ```
115
+
116
+ ```typescript
117
+ // store/slices/userSlice.ts
118
+ import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit'
119
+
120
+ interface User {
121
+ id: string
122
+ email: string
123
+ name: string
124
+ }
125
+
126
+ interface UserState {
127
+ current: User | null
128
+ status: 'idle' | 'loading' | 'succeeded' | 'failed'
129
+ error: string | null
130
+ }
131
+
132
+ const initialState: UserState = {
133
+ current: null,
134
+ status: 'idle',
135
+ error: null,
136
+ }
137
+
138
+ export const fetchUser = createAsyncThunk(
139
+ 'user/fetchUser',
140
+ async (userId: string, { rejectWithValue }) => {
141
+ try {
142
+ const response = await fetch(`/api/users/${userId}`)
143
+ if (!response.ok) throw new Error('Failed to fetch user')
144
+ return await response.json()
145
+ } catch (error) {
146
+ return rejectWithValue((error as Error).message)
147
+ }
148
+ }
149
+ )
150
+
151
+ const userSlice = createSlice({
152
+ name: 'user',
153
+ initialState,
154
+ reducers: {
155
+ setUser: (state, action: PayloadAction<User>) => {
156
+ state.current = action.payload
157
+ state.status = 'succeeded'
158
+ },
159
+ clearUser: (state) => {
160
+ state.current = null
161
+ state.status = 'idle'
162
+ },
163
+ },
164
+ extraReducers: (builder) => {
165
+ builder
166
+ .addCase(fetchUser.pending, (state) => {
167
+ state.status = 'loading'
168
+ state.error = null
169
+ })
170
+ .addCase(fetchUser.fulfilled, (state, action) => {
171
+ state.status = 'succeeded'
172
+ state.current = action.payload
173
+ })
174
+ .addCase(fetchUser.rejected, (state, action) => {
175
+ state.status = 'failed'
176
+ state.error = action.payload as string
177
+ })
178
+ },
179
+ })
180
+
181
+ export const { setUser, clearUser } = userSlice.actions
182
+ export default userSlice.reducer
183
+ ```
184
+
185
+ ### Pattern 2: Zustand with Slices (Scalable)
186
+
187
+ ```typescript
188
+ // store/slices/createUserSlice.ts
189
+ import { StateCreator } from 'zustand'
190
+
191
+ export interface UserSlice {
192
+ user: User | null
193
+ isAuthenticated: boolean
194
+ login: (credentials: Credentials) => Promise<void>
195
+ logout: () => void
196
+ }
197
+
198
+ export const createUserSlice: StateCreator<
199
+ UserSlice & CartSlice, // Combined store type
200
+ [],
201
+ [],
202
+ UserSlice
203
+ > = (set, get) => ({
204
+ user: null,
205
+ isAuthenticated: false,
206
+ login: async (credentials) => {
207
+ const user = await authApi.login(credentials)
208
+ set({ user, isAuthenticated: true })
209
+ },
210
+ logout: () => {
211
+ set({ user: null, isAuthenticated: false })
212
+ // Can access other slices
213
+ // get().clearCart()
214
+ },
215
+ })
216
+
217
+ // store/index.ts
218
+ import { create } from 'zustand'
219
+ import { createUserSlice, UserSlice } from './slices/createUserSlice'
220
+ import { createCartSlice, CartSlice } from './slices/createCartSlice'
221
+
222
+ type StoreState = UserSlice & CartSlice
223
+
224
+ export const useStore = create<StoreState>()((...args) => ({
225
+ ...createUserSlice(...args),
226
+ ...createCartSlice(...args),
227
+ }))
228
+
229
+ // Selective subscriptions (prevents unnecessary re-renders)
230
+ export const useUser = () => useStore((state) => state.user)
231
+ export const useCart = () => useStore((state) => state.cart)
232
+ ```
233
+
234
+ ### Pattern 3: Jotai for Atomic State
235
+
236
+ ```typescript
237
+ // atoms/userAtoms.ts
238
+ import { atom } from 'jotai'
239
+ import { atomWithStorage } from 'jotai/utils'
240
+
241
+ // Basic atom
242
+ export const userAtom = atom<User | null>(null)
243
+
244
+ // Derived atom (computed)
245
+ export const isAuthenticatedAtom = atom((get) => get(userAtom) !== null)
246
+
247
+ // Atom with localStorage persistence
248
+ export const themeAtom = atomWithStorage<'light' | 'dark'>('theme', 'light')
249
+
250
+ // Async atom
251
+ export const userProfileAtom = atom(async (get) => {
252
+ const user = get(userAtom)
253
+ if (!user) return null
254
+ const response = await fetch(`/api/users/${user.id}/profile`)
255
+ return response.json()
256
+ })
257
+
258
+ // Write-only atom (action)
259
+ export const logoutAtom = atom(null, (get, set) => {
260
+ set(userAtom, null)
261
+ set(cartAtom, [])
262
+ localStorage.removeItem('token')
263
+ })
264
+
265
+ // Usage
266
+ function Profile() {
267
+ const [user] = useAtom(userAtom)
268
+ const [, logout] = useAtom(logoutAtom)
269
+ const [profile] = useAtom(userProfileAtom) // Suspense-enabled
270
+
271
+ return (
272
+ <Suspense fallback={<Skeleton />}>
273
+ <ProfileContent profile={profile} onLogout={logout} />
274
+ </Suspense>
275
+ )
276
+ }
277
+ ```
278
+
279
+ ### Pattern 4: React Query for Server State
280
+
281
+ ```typescript
282
+ // hooks/useUsers.ts
283
+ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
284
+
285
+ // Query keys factory
286
+ export const userKeys = {
287
+ all: ['users'] as const,
288
+ lists: () => [...userKeys.all, 'list'] as const,
289
+ list: (filters: UserFilters) => [...userKeys.lists(), filters] as const,
290
+ details: () => [...userKeys.all, 'detail'] as const,
291
+ detail: (id: string) => [...userKeys.details(), id] as const,
292
+ }
293
+
294
+ // Fetch hook
295
+ export function useUsers(filters: UserFilters) {
296
+ return useQuery({
297
+ queryKey: userKeys.list(filters),
298
+ queryFn: () => fetchUsers(filters),
299
+ staleTime: 5 * 60 * 1000, // 5 minutes
300
+ gcTime: 30 * 60 * 1000, // 30 minutes (formerly cacheTime)
301
+ })
302
+ }
303
+
304
+ // Single user hook
305
+ export function useUser(id: string) {
306
+ return useQuery({
307
+ queryKey: userKeys.detail(id),
308
+ queryFn: () => fetchUser(id),
309
+ enabled: !!id, // Don't fetch if no id
310
+ })
311
+ }
312
+
313
+ // Mutation with optimistic update
314
+ export function useUpdateUser() {
315
+ const queryClient = useQueryClient()
316
+
317
+ return useMutation({
318
+ mutationFn: updateUser,
319
+ onMutate: async (newUser) => {
320
+ // Cancel outgoing refetches
321
+ await queryClient.cancelQueries({ queryKey: userKeys.detail(newUser.id) })
322
+
323
+ // Snapshot previous value
324
+ const previousUser = queryClient.getQueryData(userKeys.detail(newUser.id))
325
+
326
+ // Optimistically update
327
+ queryClient.setQueryData(userKeys.detail(newUser.id), newUser)
328
+
329
+ return { previousUser }
330
+ },
331
+ onError: (err, newUser, context) => {
332
+ // Rollback on error
333
+ queryClient.setQueryData(
334
+ userKeys.detail(newUser.id),
335
+ context?.previousUser
336
+ )
337
+ },
338
+ onSettled: (data, error, variables) => {
339
+ // Refetch after mutation
340
+ queryClient.invalidateQueries({ queryKey: userKeys.detail(variables.id) })
341
+ },
342
+ })
343
+ }
344
+ ```
345
+
346
+ ### Pattern 5: Combining Client + Server State
347
+
348
+ ```typescript
349
+ // Zustand for client state
350
+ const useUIStore = create<UIState>((set) => ({
351
+ sidebarOpen: true,
352
+ modal: null,
353
+ toggleSidebar: () => set((s) => ({ sidebarOpen: !s.sidebarOpen })),
354
+ openModal: (modal) => set({ modal }),
355
+ closeModal: () => set({ modal: null }),
356
+ }))
357
+
358
+ // React Query for server state
359
+ function Dashboard() {
360
+ const { sidebarOpen, toggleSidebar } = useUIStore()
361
+ const { data: users, isLoading } = useUsers({ active: true })
362
+ const { data: stats } = useStats()
363
+
364
+ if (isLoading) return <DashboardSkeleton />
365
+
366
+ return (
367
+ <div className={sidebarOpen ? 'with-sidebar' : ''}>
368
+ <Sidebar open={sidebarOpen} onToggle={toggleSidebar} />
369
+ <main>
370
+ <StatsCards stats={stats} />
371
+ <UserTable users={users} />
372
+ </main>
373
+ </div>
374
+ )
375
+ }
376
+ ```
377
+
378
+ ## Best Practices
379
+
380
+ ### Do's
381
+ - **Colocate state** - Keep state as close to where it's used as possible
382
+ - **Use selectors** - Prevent unnecessary re-renders with selective subscriptions
383
+ - **Normalize data** - Flatten nested structures for easier updates
384
+ - **Type everything** - Full TypeScript coverage prevents runtime errors
385
+ - **Separate concerns** - Server state (React Query) vs client state (Zustand)
386
+
387
+ ### Don'ts
388
+ - **Don't over-globalize** - Not everything needs to be in global state
389
+ - **Don't duplicate server state** - Let React Query manage it
390
+ - **Don't mutate directly** - Always use immutable updates
391
+ - **Don't store derived data** - Compute it instead
392
+ - **Don't mix paradigms** - Pick one primary solution per category
393
+
394
+ ## Migration Guides
395
+
396
+ ### From Legacy Redux to RTK
397
+
398
+ ```typescript
399
+ // Before (legacy Redux)
400
+ const ADD_TODO = 'ADD_TODO'
401
+ const addTodo = (text) => ({ type: ADD_TODO, payload: text })
402
+ function todosReducer(state = [], action) {
403
+ switch (action.type) {
404
+ case ADD_TODO:
405
+ return [...state, { text: action.payload, completed: false }]
406
+ default:
407
+ return state
408
+ }
409
+ }
410
+
411
+ // After (Redux Toolkit)
412
+ const todosSlice = createSlice({
413
+ name: 'todos',
414
+ initialState: [],
415
+ reducers: {
416
+ addTodo: (state, action: PayloadAction<string>) => {
417
+ // Immer allows "mutations"
418
+ state.push({ text: action.payload, completed: false })
419
+ },
420
+ },
421
+ })
422
+ ```
423
+
424
+ ## Resources
425
+
426
+ - [Redux Toolkit Documentation](https://redux-toolkit.js.org/)
427
+ - [Zustand GitHub](https://github.com/pmndrs/zustand)
428
+ - [Jotai Documentation](https://jotai.org/)
429
+ - [TanStack Query](https://tanstack.com/query)