
zustand-state-management
Zustand skill for React with TypeScript that covers store setup, persistence, and SSR hydration fixes.
- version
- 3.12.0
- GitHub stars
- 250
What it does
- Adds a
zustand-state-managementskill with 8 store templates for global state, slices, persist, devtools, and async actions - Covers the
create<T>()()TypeScript pattern,persistmiddleware for localStorage and sessionStorage, and Redux DevTools integration - Prevents five documented issues, including Next.js hydration mismatches and infinite render loops from selectors that return new objects
- Designed for React teams migrating from Redux or Context API, or building large apps with modular store architecture
Zustand state management for React with TypeScript. Use for global state, Redux/Context API migration, localStorage persistence, slices pattern, devtools, Next.js SSR, or encountering hydration errors, TypeScript inference issues, persist middleware problems, infinite render loops.
Add marketplace
/plugin marketplace add secondsky/claude-skillsRun it inside Claude Code once, then install the plugin below.
Install
/plugin install zustand-state-management@claude-skillsRun it inside Claude Code after adding the marketplace.
Files
Discovered from sourceZustand State Management
Status: Production Ready ✅ Last Updated: 2026-08-03 Latest Version: zustand@5.0.14 Dependencies: React 18+, TypeScript 5+
Quick Start (3 Minutes)
1. Install Zustand
bun add zustand # preferred
# or: npm install zustand
# or: yarn add zustand
Why Zustand?
- Minimal API: Only 1 function to learn (
create) - No boilerplate: No providers, reducers, or actions
- TypeScript-first: Excellent type inference
- Fast: Fine-grained subscriptions prevent unnecessary re-renders
- Flexible: Middleware for persistence, devtools, and more
2. Create Your First Store (TypeScript)
import { create } from 'zustand'
interface BearStore {
bears: number
increase: (by: number) => void
reset: () => void
}
const useBearStore = create<BearStore>()((set) => ({
bears: 0,
increase: (by) => set((state) => ({ bears: state.bears + by })),
reset: () => set({ bears: 0 }),
}))
CRITICAL: Notice the double parentheses create<T>()() - this is required for TypeScript with middleware.
3. Use Store in Components
import { useBearStore } from './store'
function BearCounter() {
const bears = useBearStore((state) => state.bears)
return <h1>{bears} around here...</h1>
}
function Controls() {
const increase = useBearStore((state) => state.increase)
return <button onClick={() => increase(1)}>Add bear</button>
}
Why this works:
- Components only re-render when their selected state changes
- No Context providers needed
- Selector function extracts specific state slice
The 3-Pattern Setup Process
Pattern 1: Basic Store (JavaScript)
For simple use cases without TypeScript:
import { create } from 'zustand'
const useStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
}))
When to use:
- Prototyping
- Small apps
- No TypeScript in project
Pattern 2: TypeScript Store (Recommended)
For production apps with type safety:
import { create } from 'zustand'
// Define store interface
interface CounterStore {
count: number
increment: () => void
decrement: () => void
}
// Create typed store
const useCounterStore = create<CounterStore>()((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
}))
Key Points:
- Separate interface for state + actions
- Use
create<T>()()syntax (currying for middleware) - Full IDE autocomplete and type checking
Pattern 3: Persistent Store
For state that survives page reloads:
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
interface UserPreferences {
theme: 'light' | 'dark' | 'system'
language: string
setTheme: (theme: UserPreferences['theme']) => void
setLanguage: (language: string) => void
}
const usePreferencesStore = create<UserPreferences>()(
persist(
(set) => ({
theme: 'system',
language: 'en',
setTheme: (theme) => set({ theme }),
setLanguage: (language) => set({ language }),
}),
{
name: 'user-preferences', // unique name in localStorage
storage: createJSONStorage(() => localStorage), // optional: defaults to localStorage
},
),
)
Why this matters:
- State automatically saved to localStorage
- Restored on page reload
- Works with sessionStorage too
- Handles serialization automatically
Critical Rules
Always Do
✅ Use create<T>()() (double parentheses) in TypeScript for middleware compatibility
✅ Define separate interfaces for state and actions
✅ Use selector functions to extract specific state slices
✅ Use set with updater functions for derived state: set((state) => ({ count: state.count + 1 }))
✅ Use unique names for persist middleware storage keys
✅ Handle Next.js hydration with hasHydrated flag pattern
✅ Use shallow for selecting multiple values
✅ Keep actions pure (no side effects except state updates)
Never Do
❌ Use create<T>(...) (single parentheses) in TypeScript - breaks middleware types
❌ Mutate state directly: set((state) => { state.count++; return state }) - use immutable updates
❌ Create new objects in selectors: useStore((state) => ({ a: state.a })) - causes infinite renders
❌ Use same storage name for multiple stores - causes data collisions
❌ Access localStorage during SSR without hydration check
❌ Use Zustand for server state - use TanStack Query instead
❌ Export store instance directly - always export the hook
Known Issues Prevention (5 Issues)
| Issue | Error | Quick Fix |
|---|---|---|
| #1 Hydration mismatch | "Text content does not match" | Use _hasHydrated flag + onRehydrateStorage |
| #2 TypeScript inference | Types break with middleware | Use create<T>()() double parentheses |
| #3 Import error | "createJSONStorage not exported" | Upgrade to zustand@5.0.14+ |
| #4 Infinite loop | Browser freezes | Use shallow or separate selectors |
| #5 Slices types | StateCreator types fail | Explicit StateCreator<Combined, [], [], Slice> |
Most Critical - TypeScript double parentheses:
// ❌ WRONG: create<T>((set) => ...)
// ✅ CORRECT: create<T>()((set) => ...)
See: references/known-issues.md for complete solutions with code examples.
Middleware Configuration
import { create } from 'zustand'
import { devtools, persist } from 'zustand/middleware'
const useStore = create<MyStore>()(
devtools(
persist(
(set) => ({ /* store definition */ }),
{ name: 'my-storage' },
),
{ name: 'MyStore' },
),
)
| Middleware | Purpose | Import |
|---|---|---|
persist | localStorage/sessionStorage | zustand/middleware |
devtools | Redux DevTools integration | zustand/middleware |
immer | Mutable update syntax | zustand/middleware/immer |
Order matters: devtools(persist(...)) shows persist actions in DevTools.
See: references/middleware-guide.md for complete middleware documentation.
Common Patterns
| Pattern | Use Case | Key Technique |
|---|---|---|
| Computed values | Derived data | Compute in selector: state.items.length |
| Async actions | API calls | set({ isLoading: true }) + try/catch |
| Reset store | Logout, form clear | set(initialState) |
| Selector with params | Dynamic access | state.todos.find(t => t.id === id) |
| Multiple stores | Separation of concerns | Create separate create() calls |
See: references/common-patterns.md for complete implementations.
Advanced Topics
| Topic | Use Case | Key API |
|---|---|---|
| Vanilla store | Non-React, testing | createStore() from zustand/vanilla |
| Custom middleware | Logging, timestamps | Wrap StateCreator |
| Immer | Mutable update syntax | immer() middleware |
| Subscriptions | Side effects | store.subscribe() |
See: references/advanced-topics.md for complete implementations.
Bundled Resources
| Type | Files |
|---|---|
| Templates | basic-store.ts, typescript-store.ts, persist-store.ts, slices-pattern.ts, devtools-store.ts, nextjs-store.ts, computed-store.ts, async-actions-store.ts |
| References | middleware-guide.md, typescript-patterns.md, nextjs-hydration.md, migration-guide.md, known-issues.md, common-patterns.md, advanced-topics.md |
When to Load References
| Reference | Load When... |
|---|---|
known-issues.md | Debugging hydration, TypeScript, infinite loop, or slices errors |
common-patterns.md | Implementing computed values, async actions, reset patterns |
advanced-topics.md | Vanilla stores, custom middleware, Immer, subscriptions |
middleware-guide.md | Configuring persist, devtools, or combining middlewares |
typescript-patterns.md | Complex type inference issues, StateCreator problems |
nextjs-hydration.md | Next.js SSR/hydration problems |
migration-guide.md | Migrating from Redux, Context API, or Zustand v4 |
Quick Troubleshooting
| Problem | Solution |
|---|---|
| Store updates don't trigger re-renders | Use selector: useStore(state => state.value) not destructuring |
| TypeScript errors with middleware | Use create<T>()() double parentheses |
| Hydration error with persist | Implement _hasHydrated flag pattern |
| Actions not showing in DevTools | Pass action name: set(newState, undefined, 'actionName') |
| Store resets unexpectedly | HMR causes reset in development |
Dependencies
{ "dependencies": { "zustand": "^5.0.14", "react": "^18.0.0+" } }
Compatibility: React 18+, React 19, TypeScript 5+, Next.js 14+, Vite 5+
Official Docs: https://zustand.docs.pmnd.rs/ | GitHub: https://github.com/pmndrs/zustand
Readme
Zustand State Management
Status: Production Ready ✅ Last Updated: 2025-10-24 Production Tested: Used across 2025 React ecosystem, React 19 compatible
Auto-Trigger Keywords
Claude Code automatically discovers this skill when you mention:
Primary Keywords
- zustand
- zustand state management
- state management React
- create store
- useBoundStore
- zustand v5
- StateCreator
Secondary Keywords
- global state React
- React state management
- persist middleware
- devtools middleware
- slices pattern
- zustand TypeScript
- zustand hooks
- useState alternative
- Redux alternative
- Context API alternative
- localStorage state
- sessionStorage state
- shallow equality
- selector pattern
- zustand immer
Error-Based Keywords
- "hydration error" zustand
- "text content mismatch" zustand
- "TypeScript inference" zustand
- "infinite render" zustand
- "StateCreator" types
- "create()" syntax
- "createJSONStorage not exported"
- "persist middleware error"
- "Next.js hydration" zustand
What This Skill Does
Provides production-tested patterns for Zustand state management in React with TypeScript. Covers basic setup, middleware configuration (persist, devtools), slices pattern for modular stores, Next.js SSR handling, and advanced TypeScript patterns.
Core Capabilities
✅ TypeScript Setup - Correct create<T>()() syntax with full type inference
✅ Persist Middleware - localStorage/sessionStorage with hydration handling
✅ Slices Pattern - Modular store organization for large apps
✅ Next.js Integration - SSR-safe stores with hydration checks
✅ Devtools - Redux DevTools integration for debugging
✅ Common Patterns - Async actions, computed values, selectors, resets
✅ Error Prevention - Prevents 5 documented issues with production-tested solutions
✅ 8 Templates - Ready-to-use store patterns for every use case
Known Issues This Skill Prevents
| Issue | Why It Happens | Source | How Skill Fixes It |
|---|---|---|---|
| Next.js Hydration Mismatch | Persist middleware reads localStorage on client but not server | DEV.to | _hasHydrated flag pattern |
| TypeScript Double Parentheses | Missing currying syntax breaks middleware types | Official TypeScript Guide | Always use create<T>()() |
| Persist Import Error | Wrong import path or version mismatch | GitHub #2839 | Correct imports for v5 documented |
| Infinite Render Loop | Creating new objects in selectors | GitHub #2642 | Use shallow or select primitives |
| Slices TypeScript Complexity | Complex StateCreator types fail | Official Slices Guide | Explicit type annotations provided |
When to Use This Skill
✅ Use When:
- Setting up global state in React applications
- Migrating from Redux or Context API to simpler solution
- Need state persistence (localStorage/sessionStorage)
- Building type-safe stores with TypeScript
- Working with Next.js and need SSR-safe state
- Want devtools integration for debugging
- Building large apps needing modular store architecture (slices)
- Encountering hydration errors or TypeScript issues
❌ Don't Use When:
- Managing server state (use TanStack Query instead)
- Need time-travel debugging (use Redux)
- Working with non-React frameworks (check Zustand vanilla store)
- Only need local component state (use useState)
Quick Usage Example
# Install Zustand (Bun preferred)
bun add zustand # preferred
# or: npm install zustand
# Create store
cat > src/store.ts << 'EOF'
import { create } from 'zustand'
interface BearStore {
bears: number
increase: () => void
}
export const useBearStore = create<BearStore>()((set) => ({
bears: 0,
increase: () => set((state) => ({ bears: state.bears + 1 })),
}))
EOF
# Use in component
cat > src/App.tsx << 'EOF'
import { useBearStore } from './store'
function App() {
const bears = useBearStore((state) => state.bears)
const increase = useBearStore((state) => state.increase)
return (
<div>
<h1>{bears} bears</h1>
<button onClick={increase}>Add bear</button>
</div>
)
}
EOF
Result: Type-safe, minimal global state with zero boilerplate
Full instructions: See SKILL.md
Package Versions (Verified 2025-10-24)
| Package | Version | Status |
|---|---|---|
| zustand | 5.0.14 | ✅ Latest stable |
| react | 19.0.0 | ✅ Compatible |
| typescript | 5.0+ | ✅ Supported |
Dependencies
Prerequisites: None (standalone skill)
Integrates With:
- tanstack-query (server state management - use together)
- react-hook-form (form state with Zustand as global state)
- tailwind-v4-shadcn (UI components with Zustand state)
File Structure
zustand-state-management/
├── SKILL.md # Complete documentation
├── README.md # This file
├── scripts/ # Version checking
│ └── check-versions.sh
├── references/ # Deep-dive docs
│ ├── middleware-guide.md
│ ├── typescript-patterns.md
│ ├── nextjs-hydration.md
│ └── migration-guide.md
└── templates/ # 8 ready-to-use stores
├── basic-store.ts
├── typescript-store.ts
├── persist-store.ts
├── slices-pattern.ts
├── devtools-store.ts
├── nextjs-store.ts
├── computed-store.ts
└── async-actions-store.ts
Official Documentation
- Zustand: https://zustand.docs.pmnd.rs/
- GitHub: https://github.com/pmndrs/zustand
- TypeScript Guide: https://zustand.docs.pmnd.rs/guides/typescript
- Context7 Library:
/pmndrs/zustand
Related Skills
- tanstack-query - Server state management (planned)
- react-hook-form-zod - Forms with validation (planned)
- tailwind-v4-shadcn - UI components
Contributing
Found an issue or have a suggestion?
- Open an issue: https://github.com/secondsky/claude-skills/issues
- See SKILL.md for detailed documentation
License
MIT License - See main repo LICENSE file
Production Tested: React 19 compatible, used across 2025 React ecosystem Token Savings: ~65% Error Prevention: 100% (all 5 known issues prevented) Ready to use! See SKILL.md for complete setup.
Details
- Marketplace
- secondsky/claude-skills
- Source
- plugins/zustand-state-management
- Category
- Frontend
- Keywords
- zustand-state-management, zustand, state, management, frontend, components, ssr, migration
- Listed since
- Apr 7, 2026
More from secondsky/claude-skills
All 122- aceternity-uiv3.12.0
- api-authenticationv3.12.0
- api-changelog-versioningv3.12.0
- api-contract-testingv3.12.0
- api-design-principlesv3.12.0
- api-error-handlingv3.12.0
- api-filtering-sortingv3.12.0
- api-gateway-configurationv3.12.0
- api-paginationv3.12.0
- api-rate-limitingv3.12.0
- api-reference-documentationv3.12.0
- api-response-optimizationv3.12.0
- api-security-hardeningv3.12.0
- api-testingv3.12.0
- api-versioning-strategyv3.12.0
- app-store-deploymentv3.12.0
- architecture-patternsv3.12.0
- auto-animatev3.12.0
- base-ui-reactv3.12.0
- bunv3.12.0
- claude-code-bash-patternsv3.12.0
- claude-hook-writerv3.12.0
- clefcut-cloudflare-remotion-videov3.12.0
- clefcut-cloudflare-videov3.12.0
Similar to zustand-state-management
More Frontend & UI Code
zustandPluginTheBushidoCollective/han201 starsComprehensive Zustand state management skills for React applications with store patterns, middleware, and TypeScript integration.
react-state-managementSkillwshobson/agents16.1K installsChoose between Redux Toolkit, Zustand, Jotai, and React Query for global and server state in React.
tanstack-queryPluginsecondsky/claude-skills250 starsTanStack Query v5 (React Query) server state management. Use for data fetching, caching, mutations, or encountering v4 migration, stale data, invalidation error
zustand-patternsSkillyonatangross/orchestkit1.5K installsZustand 5.x state management reference covering slices, middleware, Immer, persistence, and selectors with TypeScript.
pinia-v3Pluginsecondsky/claude-skills250 starsPinia v3 Vue state management with defineStore, getters, actions. Use for Vue 3 stores, Nuxt SSR, Vuex migration, or encountering store composition, hydration,
react-toolkitPluginarmanzeroeight/fastagent-plugins29 starsReact development toolkit for component architecture, state management, and performance optimization. Includes react architect agent for strategic React decisio