secondsky/claude-skills / plugins/zustand-state-management/skills/zustand-state-management
zustand-state-management
VerifiedZustand 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.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 9.7 KB |
| assets/example-template.txt | markdown | 416 B |
| references/advanced-topics.md | markdown | 7.9 KB |
| references/common-patterns.md | markdown | 6.4 KB |
| references/example-reference.md | markdown | 760 B |
| references/known-issues.md | markdown | 5.4 KB |
| references/middleware-guide.md | markdown | 5.2 KB |
| references/migration-guide.md | markdown | 6.2 KB |
| references/nextjs-hydration.md | markdown | 5.0 KB |
| references/typescript-patterns.md | markdown | 4.9 KB |
| scripts/check-versions.shexecutable | script | 3.6 KB |
| scripts/example-script.shexecutable | script | 302 B |
| templates/async-actions-store.ts | script | 7.6 KB |
| templates/basic-store.ts | script | 908 B |
| templates/computed-store.ts | script | 5.6 KB |
| templates/devtools-store.ts | script | 3.4 KB |
| templates/nextjs-store.ts | script | 2.6 KB |
| templates/persist-store.ts | script | 2.8 KB |
| templates/slices-pattern.ts | script | 5.0 KB |
| templates/typescript-store.ts | script | 1.8 KB |
references/nextjs-hydration.md
View on GitHub# Zustand + Next.js Hydration Guide
Complete guide for using Zustand with Next.js SSR. Load for Next.js-specific problems.
---
## The Hydration Problem
**Error**: `"Text content does not match server-rendered HTML"`
**Why it happens**:
- Server renders with default state
- Client loads persisted state from localStorage
- Content doesn't match → hydration error
---
## Solution: Hydration Flag Pattern
### Store Setup
```typescript
'use client'
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
interface Store {
_hasHydrated: boolean // Track hydration
count: number
setHasHydrated: (hydrated: boolean) => void
increment: () => void
}
export const useStore = create<Store>()(
persist(
(set) => ({
_hasHydrated: false,
count: 0,
setHasHydrated: (hydrated) => set({ _hasHydrated: hydrated }),
increment: () => set((state) => ({ count: state.count + 1 })),
}),
{
name: 'storage',
onRehydrateStorage: () => (state) => {
state?.setHasHydrated(true) // Set true when done
},
},
),
)
```
### Component Usage
```typescript
'use client'
function Component() {
const hasHydrated = useStore((state) => state._hasHydrated)
const count = useStore((state) => state.count)
if (!hasHydrated) {
return <div>Loading...</div>
}
return <div>Count: {count}</div>
}
```
---
## Alternative: Accept Flash
If loading state is unacceptable, accept brief flash:
```typescript
'use client'
function Component() {
const count = useStore((state) => state.count)
// Will show default (0) briefly, then correct value
return <div>Count: {count}</div>
}
```
**Trade-off**: Simpler code, but user sees flash.
---
## App Router vs Pages Router
### App Router (Recommended)
```typescript
// app/layout.tsx
export default function RootLayout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
// app/page.tsx
'use client'
import { useStore } from './store'
export default function Page() {
return <Component />
}
```
**Note**: Add `'use client'` to components using Zustand.
### Pages Router
```typescript
// pages/_app.tsx
export default function App({ Component, pageProps }) {
return <Component {...pageProps} />
}
// pages/index.tsx
import { useStore } from '../store'
export default function Page() {
return <Component />
}
```
**Note**: No `'use client'` needed in Pages Router.
---
## Server Components
**NEVER** use Zustand in Server Components:
```typescript
// ❌ WRONG - Server Component
export default async function ServerComponent() {
const count = useStore((state) => state.count) // Error!
return <div>{count}</div>
}
// ✅ CORRECT - Client Component
'use client'
export default function ClientComponent() {
const count = useStore((state) => state.count)
return <div>{count}</div>
}
```
---
## SSR with getServerSideProps
```typescript
// pages/index.tsx
import { GetServerSideProps } from 'next'
export const getServerSideProps: GetServerSideProps = async () => {
// Fetch data on server
const data = await fetchData()
return {
props: { data },
}
}
export default function Page({ data }) {
const setData = useStore((state) => state.setData)
// Sync server data to store
useEffect(() => {
setData(data)
}, [data, setData])
return <Component />
}
```
---
## Common Patterns
### Initialize Store from Props
```typescript
'use client'
function Page({ serverData }) {
const setData = useStore((state) => state.setData)
useEffect(() => {
setData(serverData)
}, [serverData, setData])
return <Component />
}
```
### Conditional Rendering
```typescript
'use client'
function Component() {
const hasHydrated = useStore((state) => state._hasHydrated)
const theme = useStore((state) => state.theme)
return (
<div className={hasHydrated ? theme : 'default'}>
{hasHydrated ? <Content /> : <Skeleton />}
</div>
)
}
```
### Progressive Enhancement
```typescript
'use client'
function Component() {
const hasHydrated = useStore((state) => state._hasHydrated)
const preferences = useStore((state) => state.preferences)
// Always render, but enhance after hydration
return (
<div>
<DefaultUI />
{hasHydrated && <EnhancedUI preferences={preferences} />}
</div>
)
}
```
---
## Debugging Hydration Errors
### Enable Strict Mode
```typescript
// next.config.js
module.exports = {
reactStrictMode: true,
}
```
### Check for Differences
```typescript
useEffect(() => {
console.log('Server state:', defaultState)
console.log('Client state:', persistedState)
}, [])
```
### Use React DevTools
Look for red warnings about hydration mismatches.
---
## Official Resources
- **Next.js Hydration**: https://nextjs.org/docs/messages/react-hydration-error
- **Zustand Persist**: https://github.com/pmndrs/zustand/blob/main/docs/integrations/persisting-store-data.md
- **DEV.to Guide**: https://dev.to/abdulsamad/how-to-use-zustands-persist-middleware-in-nextjs-4lb5
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirements | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |