Skip to main content
skill CX Codex

zustand-state-management · secondsky — Claude Code skill: setup guide

zustand-state-management guides agent setup of Zustand v5 stores for React 18+ and TypeScript 5+. Fixes Next.js hydration mismatches and prevents selector re-render loops.

MIT 301 installs ★ 250 updated 2026-10-20

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add secondsky/claude-skills --skill zustand-state-management -a claude-code
Open on GitHub

What zustand-state-management does

The skill guides your agent through building Zustand stores using tested TypeScript patterns. It enforces curried create<T>()() syntax. Skipping the second set of parentheses immediately breaks type inference when middleware enters the stack.

Rules cover store persistence with localStorage, Redux DevTools integration, and slice composition. For Next.js projects, the skill applies the _hasHydrated flag pattern during SSR. Accessing browser storage directly on the server without this check triggers hydration errors.

It also regulates selectors. Creating raw inline objects inside selectors triggers infinite re-renders, so the skill mandates separate selectors or shallow equality checks.

What it helps with

  • build typed stores using curried create<T>()() syntax
  • persist state across reloads with persist middleware
  • fix Next.js hydration text mismatches using _hasHydrated
  • connect Redux DevTools alongside immer middleware

Example prompts for the agent

  • Create a typed Zustand store for user settings with localStorage persistence
  • Fix infinite re-renders caused by object selectors in our Zustand store
  • Configure Zustand middleware with Redux DevTools and proper TypeScript types

How to install zustand-state-management

1Skills CLI (Vercel)

npx skills add secondsky/claude-skills --skill zustand-state-management -a claude-code

2Manually: put the files in place

~/.claude/skills/zustand-state-management/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/zustand-state-management/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about zustand-state-management

How to install zustand-state-management in Claude Code?

Run npx skills add secondsky/claude-skills --skill zustand-state-management -a claude-code.

What does zustand-state-management do?

It guides assistants in configuring Zustand v5 stores in React 18+ projects with TypeScript 5+. It prevents common selector loops and middleware typing issues.

Why does the store require double parentheses create<T>()()?

TypeScript requires the curried format to infer store types when combining middlewares like persist and devtools. Single parentheses break type checking.

Source text

SKILL.md · MIT
---
name: zustand-state-management
description: "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."

metadata:
  keywords:
    - zustand
    - state management
    - React state
    - TypeScript state
    - persist middleware
    - devtools
    - slices pattern
    - global state
    - React hooks
    - create store
    - useBoundStore
    - StateCreator
    - hydration error
    - text content mismatch
    - infinite render
    - localStorage
    - sessionStorage
    - immer middleware
    - shallow equality
    - selector pattern
    - zustand v5

license: MIT
---
# Zustand State Management

**Status**: Production Ready ✅
**Last Updated**: 2026-08-03
**Latest Version**: [email protected]
**Dependencies**: React 18+, TypeScript 5+

---

## Quick Start (3 Minutes)

### 1. Install Zustand

```bash
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)

```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

```tsx
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:

```javascript
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:

```typescript
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:

```typescript
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 [email protected]+ |
| **#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:
```typescript
// ❌ WRONG: create<T>((set) => ...)
// ✅ CORRECT: create<T>()((set) => ...)
```

**See**: `references/known-issues.md` for complete solutions with code examples.

---

## Middleware Configuration

```typescript
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

```json
{ "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

© secondsky · MIT · secondsky/claude-skills

Similar skills

All skills for Frontend and UI →

zustand-state-management by other authors comes first.

zustand-state-management Mindrally zustand-state-management enforces Zustand store best practices in React and TypeScript apps, covering store slices, SSR, and testing. It helps eliminate selector re-renders and hydration bugs. CX Codex +1 1,000installs zustand-state-builder patricio0312rev zustand-state-builder — a skill for managing app state with Zustand: minimal API, full TypeScript support, persistence, and devtools. Runs on Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, and OpenCode. CX Codex +1 264installs state-management agent-skills state-management is a Claude Code skill for handling data fetching, caching, and client-side state with React Query and Zustand. It activates around useQuery, useMutation, Zustand stores, and state-management tasks. CX Codex +1 849installs frontend-state-management aj-geddes Guides your agent through frontend state management: Redux, MobX, Zustand or the Context API. CX Codex +1 487installs zustand-state existential-birds zustand-state — a skill for Zustand, a lightweight state-management library for React and vanilla JavaScript. CX Codex +1 261installs zustand-patterns OrchestKit zustand-patterns — a skill for Claude Code enforces TypeScript-first patterns for Zustand 5.x state management. Triggers during store creation, slice composition, and middleware setup. CX Codex +1 1,500installs zustand-5 prowler-cloud Zustand 5 state management patterns for Claude Code: basic stores, selectors, persist middleware, and slice composition. Prevents unnecessary re-renders and keeps state logic clean. CX Codex +1 912installs

From the same set138

The whole set →
cloudflare-workers-multi-lang cloudflare-workers-multi-lang guides Cloudflare Workers development in Rust, Python, and WebAssembly. Useful when offloading heavy computation to WASM modules. CX Codex +1 317installs cloudflare-r2 Skill for working with Cloudflare R2, an S3-compatible object storage. Manages buckets, uploads, CORS and presigned URLs — everything needed to handle files in the cloud. CX Codex +1 316installs cloudflare-workers-migration cloudflare-workers-migration — a skill for porting applications to Cloudflare Workers from AWS Lambda, Vercel, Express and Node.js. Adapts handlers, middleware and environment variables to Web APIs. CX Codex +1 316installs tanstack-query This skill guides Claude Code through TanStack Query v5 for fetching, caching, mutations, and v4 migration issues in React projects. CX Codex +1 314installs nextjs Skill for Next.js 16 and React 19.2 with App Router, Server Components, Server Actions, and caching patterns. Handles migration from version 15, async params errors, and Partial Prerendering setup. CX Codex +1 299installs feature-dev The feature-dev skill guides feature work through seven phases, from codebase discovery to review. Use it for multi-file changes and unclear architecture decisions. CX Codex +1 294installs cloudflare-nextjs The cloudflare-nextjs skill guides Next.js deployments to Cloudflare Workers with OpenNext. Use it to migrate a project or troubleshoot Workers-specific configuration and runtime issues. CX Codex +1 267installs cloudflare-turnstile cloudflare-turnstile is a Claude Code skill for adding Turnstile and checking tokens on the server. It activates for bot protection work, widget errors, and CSP or token validation failures. CX Codex +1 261installs

Project sponsors

Companies that keep this analytics open