zustand-state-management
Skill266 starsChanged 10 months agoApache-2.0View on GitHub
Best practices for Zustand state management in React and TypeScript applications, covering store design, selectors, middleware, SSR, and testing. Use when creating or refactoring Zustand stores, deciding whether state belongs in Zustand vs component state vs a server-state library, optimizing selector re-renders, adding persist/devtools/immer middleware, or handling Zustand with SSR/React Server Components.
3 other projects use a version of this.
Adopted by
Most recently taken up by
- codecharmhq/claude-code-skillstheir own version, first seen May 17, 2026
- Aver005/agent-skillstheir own version, first seen Feb 14, 2026
- JasonPaff/clarifytheir own version, first seen Feb 4, 2026
Other versions3 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 3
- Aver005/agent-skills★ 2same name
- codecharmhq/claude-code-skills★ 1same name
- JasonPaff/clarify★ 0same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository264 other files it gives its agents.
- accessibility-a11ySkill
- alpine-jsSkill
- analytics-data-analysisSkill
- android-developmentSkill
- angular-developmentSkill
- angularSkill
- anime-jsSkill
- anthropic-claude-developmentSkill
- api-developmentSkill
- apollo-graphqlSkill
- aspnet-coreSkill
- astroSkill
- auth0-authenticationSkill
- autogen-developmentSkill
- automl-hyperparameter-optimizationSkill
- aws-developmentSkill
- azureSkill
- backend-developmentSkill
- bash-scriptingSkill
- beautifulsoup-parsingSkill
- bitbucket-workflowSkill
- blazorSkill
- blender-python-addonSkill
- blockchainSkill
- bootstrapSkill
- business-central-developmentSkill
- cheerio-parsingSkill
- chrome-extension-developmentSkill
- ci-cd-best-practicesSkill
- clean-architectureSkill
- clean-codeSkill
- clerk-authenticationSkill
- cloudflare-developmentSkill
- computer-vision-opencvSkill
- convexSkill
- cppSkill
- c-sharpSkill
- cssSkill
- cypressSkill
- data-analysis-jupyterSkill
- data-analystSkill
- data-jupyter-pythonSkill
- deep-learning-pythonSkill
- deep-learning-pytorchSkill
- deep-learningSkill
- deno-typescriptSkill
- design-systemsSkill
- devopsSkill
- django-pythonSkill
- django-rest-api-developmentSkill
- dockerSkill
- dotnetSkill
- drizzle-ormSkill
- drupal-developmentSkill
- elasticsearch-best-practicesSkill
- electron-developmentSkill
- elixirSkill
- embedded-stm32Skill
- esbuild-bundlerSkill
- ethereumSkill
- The first 60 shown.
The file
Show its rules and text
We split this skill into the rules it gives an agent
27 rules. About 0 are common, 17 are distinctive, and 10 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈17
Distinctive · estimate
This author's own choices. Worth a look.
10
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 12
Keep ephemeral UI state in the nearest component with useState or useReducer — don't reach for Zustand by default.
- Distinctive: line 13
Use URL state for shareable filters, pagination, tabs, and search params.
- Distinctive: line 14
Use Zustand only for client state that is genuinely shared across unrelated components (auth session view state, command palette, cart …
- Distinctive: line 15
Use TanStack Query, SWR, RTK Query, or the project's existing data layer for server state — don't duplicate fetched server data into a …
- Distinctive: line 21
Keep stores small and domain-focused rather than one global store for the entire application.
- Distinctive: line 23
Keep derived values as selectors or small pure helpers unless they must be cached in state.
- Distinctive: line 54
Do not call a store hook without a selector in components unless the component truly needs every field.
- Very specific: line 55
Use useShallow (from zustand/react/shallow) when a selector returns an object or tuple of multiple values, to avoid re-renders from a new …
- Distinctive: line 56
Keep selectors pure and cheap.
- Very specific: line 81
Avoid any; use unknown plus narrowing for external data.
- Distinctive: line 83
Prefer discriminated unions for complex local status instead of several loosely related booleans.
- Very specific: line 89
Use functional set((state) => nextState) when the next value depends on current state.
- Very specific: line 90
Treat nested state immutably.
- Very specific: line 105
Use persist only for state that must survive reloads.
- Very specific: line 106
Use partialize, version, and migrate when persisting anything beyond trivial preferences.
- Distinctive: line 107
Never persist secrets, access tokens, refresh tokens, raw PII, or other long-lived authorization state to browser storage.
- Very specific: line 119
Use devtools in development for complex flows and give important actions clear names so they're identifiable in the trace.
- Very specific: line 122
Use subscribeWithSelector for non-React subscriptions that need fine-grained updates outside of component rendering.
- Distinctive: line 133
Do not read or mutate browser-only stores from React Server Components.
- Very specific: line 136
Keep store modules free of direct window, document, and storage access outside middleware configuration.
- Distinctive: line 140
Test stores independently of components — test store actions directly without rendering React when possible.
- Distinctive: line 144
Test middleware behavior (persistence, devtools) separately from core store logic.
- Distinctive: line 148
Do not create one global store for the entire application.
- Distinctive: line 149
Do not put form input state in Zustand unless multiple distant components edit the same draft.
- Distinctive: line 150
Do not mutate nested objects directly without Immer middleware.
- Distinctive: line 151
Do not use Zustand as an event bus.
- Distinctive: line 152
Do not introduce Redux-style reducers, action constants, or dispatch wrappers unless the project already uses that pattern.
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Zustand State Management
This skill covers designing and using Zustand stores in React and TypeScript applications, including state ownership decisions, store slicing, selector performance, middleware, SSR, and testing.
State Ownership
- Keep ephemeral UI state in the nearest component with
useStateoruseReducer— don't reach for Zustand by default. - Use URL state for shareable filters, pagination, tabs, and search params.
- Use Zustand only for client state that is genuinely shared across unrelated components (auth session view state, command palette, cart draft, editor state, etc.).
- Use TanStack Query, SWR, RTK Query, or the project's existing data layer for server state — don't duplicate fetched server data into a Zustand store unless there's a documented offline or draft-editing requirement.
- Implement functional, declarative patterns; avoid classes. Use descriptive variable names with auxiliary verbs like
isLoading,hasError.
Store Design
- Model each store as state plus named actions; avoid exposing anonymous setters for component code to misuse.
- Keep stores small and domain-focused rather than one global store for the entire application.
- Split large stores into typed slices, then apply middleware only at the composed store boundary.
- Keep derived values as selectors or small pure helpers unless they must be cached in state.
- Store serializable data by default; keep DOM nodes, promises, sockets, and timers outside store state.
import { create } from 'zustand'
interface SidebarState {
isOpen: boolean
activePanelId: string | null
}
interface SidebarActions {
openPanel: (panelId: string) => void
close: () => void
toggle: () => void
}
type SidebarStore = SidebarState & SidebarActions
export const useSidebarStore = create<SidebarStore>()((set) => ({
isOpen: false,
activePanelId: null,
openPanel: (panelId) => set({ isOpen: true, activePanelId: panelId }),
close: () => set({ isOpen: false, activePanelId: null }),
toggle: () => set((state) => ({ isOpen: !state.isOpen })),
}))Component Usage & Performance
- Subscribe to the smallest possible slice:
useStore((state) => state.value). Avoid selecting the entire store. - Do not call a store hook without a selector in components unless the component truly needs every field.
- Use
useShallow(fromzustand/react/shallow) when a selector returns an object or tuple of multiple values, to avoid re-renders from a new object reference each call. - Keep selectors pure and cheap; move expensive derivations into memoized helpers.
import { useShallow } from 'zustand/react/shallow'
import { useSidebarStore } from '@/stores/sidebar-store'
export function SidebarToggle() {
const { isOpen, toggle } = useSidebarStore(
useShallow((state) => ({
isOpen: state.isOpen,
toggle: state.toggle,
})),
)
return (
<button type="button" aria-expanded={isOpen} onClick={toggle}>
Toggle sidebar
</button>
)
}TypeScript
- Define explicit state and action interfaces for shared stores; combine them (
type Store = State & Actions) rather than one flat interface for non-trivial stores. - Avoid
any; useunknownplus narrowing for external data. - Type action payloads and return values, including async actions.
- Prefer discriminated unions for complex local status instead of several loosely related booleans.
- Export store state types when tests, utilities, or vanilla store factories need them.
Middleware
Updates
- Use functional
set((state) => nextState)when the next value depends on current state. - Treat nested state immutably; install and use the
immermiddleware only when it materially simplifies nested updates — don't mutate nested objects directly without it.
Persistence
import { persist } from 'zustand/middleware'
const useStore = create(
persist(
(set) => ({
// state and actions
}),
{ name: 'store-key' }
)
)- Use
persistonly for state that must survive reloads. - Use
partialize,version, andmigratewhen persisting anything beyond trivial preferences. - Never persist secrets, access tokens, refresh tokens, raw PII, or other long-lived authorization state to browser storage.
DevTools
import { devtools } from 'zustand/middleware'
const useStore = create(
devtools((set) => ({
// state and actions
}))
)- Use
devtoolsin development for complex flows and give important actions clear names so they're identifiable in the trace.
Non-React Subscriptions
- Use
subscribeWithSelectorfor non-React subscriptions that need fine-grained updates outside of component rendering.
Async Actions & Error Handling
- Async store actions should coordinate client-only workflows, optimistic drafts, or local device APIs — keep HTTP fetching in the project's server-state layer unless the state is explicitly client-owned.
- Represent async client workflows with explicit statuses such as
idle,pending,success, anderrorrather than ad hoc booleans. - Handle errors at function start using early returns and guard clauses; use try-catch in async actions and provide meaningful error messages.
- Reset error state deliberately when retrying or closing a workflow.
SSR and React Server Components
- Do not read or mutate browser-only stores from React Server Components.
- In SSR frameworks (Next.js App Router, etc.), create per-request vanilla stores when state must be initialized on the server, rather than a shared module-level store.
- Guard persisted stores against hydration mismatches before rendering storage-backed values.
- Keep store modules free of direct
window,document, and storage access outside middleware configuration.
Testing
- Test stores independently of components — test store actions directly without rendering React when possible.
- Reset stores between tests with their initial state.
- Assert selectors and actions separately from component behavior; mock Zustand stores in component tests when isolating UI logic.
- Mock server-state libraries instead of routing fetched data through Zustand for tests.
- Test middleware behavior (persistence, devtools) separately from core store logic.
Anti-Patterns
- Do not create one global store for the entire application.
- Do not put form input state in Zustand unless multiple distant components edit the same draft.
- Do not mutate nested objects directly without Immer middleware.
- Do not use Zustand as an event bus; prefer explicit callbacks, services, or a scoped store.
- Do not introduce Redux-style reducers, action constants, or dispatch wrappers unless the project already uses that pattern.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

