Skills DirectorySkills Directory
SkillsLearnSecurityCategoriesDocsBlogPro
Sign InSubmit Skill
Skills Directory

Security-tested agent skills for Claude, coding agents, and AI workflows.

Directory

  • Browse Skills
  • All Skills A–Z
  • Claude Skills
  • Claude Code Skills
  • Agent Skills
  • Categories
  • Authors
  • Submit a Skill

Learn

  • Learn Hub
  • Install Claude Skills
  • Write SKILL.md
  • Skills vs MCP
  • Directories Compared

Security

  • Security
  • Methodology
  • Secure Claude Skills
  • Security Badges
  • Chrome Extension
  • Skill Manager

Company

  • About
  • Community
  • Blog
  • API Docs
  • Advertise

2026 Skills Directory. All rights reserved.

ProTermsPrivacyRefunds
Back to skills

React Zustand Patterns

ASecurity

Zustand state management patterns for React. Use when working with Zustand stores, debugging state timing issues, or implementing async actions. Works for both React web and React Native.

416 stars
0 votes
0 copies
0 views
Added 2/7/2026
developmenttypescriptreacttestingdebuggingapi

Works with

api

Security Analysis

A100/100

Pro scans all 2 files and shows the line behind each finding

Scanned 2/12/2026

$npx -y skills add aiskillstore/marketplace --skill react-zustand-patterns --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of React Zustand Patterns?

Add the live security badge to your README — it updates automatically with every re-scan.

Security grade badge for React Zustand Patterns
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/aiskillstore-react-zustand-patterns/badge)](https://www.skillsdirectory.com/skills/aiskillstore-react-zustand-patterns)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
Files
SKILL.md
---
name: react-zustand-patterns
description: Zustand state management patterns for React. Use when working with Zustand stores, debugging state timing issues, or implementing async actions. Works for both React web and React Native.
---

# Zustand Patterns for React

## Problem Statement

Zustand's simplicity hides important timing details. `set()` is synchronous, but React re-renders are batched. `getState()` escapes stale closures. Async actions in stores need careful handling. Understanding these internals prevents subtle bugs.

---

## Pattern: set() is Synchronous, Renders are Batched

**Problem:** Assuming state is "ready" for React immediately after `set()`.

```typescript
const useStore = create((set, get) => ({
  count: 0,

  increment: () => {
    set({ count: get().count + 1 });
    // State IS updated here (set is sync)
    console.log(get().count); // ✅ Shows new value

    // But React hasn't re-rendered yet
    // Component will see old value until next render cycle
  },
}));
```

**Key insight:**
- `set()` updates the store synchronously
- `getState()` immediately reflects the new value
- React components re-render asynchronously (batched)

**When this matters:**
- Chaining multiple state updates
- Validating state after update
- Debugging "stale" component values

---

## Pattern: getState() Escapes Stale Closures

**Problem:** Callbacks and async functions capture state at creation time. Using `get()` or `getState()` always gets current state.

```typescript
const useStore = create((set, get) => ({
  data: {},

  // WRONG - closure captures stale state
  saveDataBad: (id: string, value: number) => {
    setTimeout(() => {
      // If someone passed `data` as a parameter, it would be stale
    }, 1000);
  },

  // CORRECT - always use get() for current state
  saveData: async (id: string, value: number) => {
    await someAsyncOperation();
    // After await, use get() to ensure current state
    const currentData = get().data;
    set({ data: { ...currentData, [id]: value } });
  },
}));

// In components - same principle
function Component() {
  const data = useStore((s) => s.data);

  const handleSave = async () => {
    await delay(1000);
    // data here is stale! Captured at render time

    // Use getState() for current value
    const current = useStore.getState().data;
  };
}
```

**Rule:** After any `await`, use `get()` or `getState()` - never rely on closure-captured values.

---

## Pattern: Async Actions in Stores

**Problem:** Async actions need explicit `async/await` and careful state reads after awaits.

```typescript
const useStore = create((set, get) => ({
  loading: false,
  data: null,
  error: null,

  // WRONG - no async keyword, race condition prone
  fetchDataBad: (id: string) => {
    set({ loading: true });
    api.fetch(id).then((data) => {
      set({ data, loading: false });
    });
    // Returns immediately, caller can't await
  },

  // CORRECT - proper async action
  fetchData: async (id: string) => {
    set({ loading: true, error: null });

    try {
      const data = await api.fetch(id);
      // Re-read state after await if needed
      if (get().loading) { // Check we're still in loading state
        set({ data, loading: false });
      }
    } catch (error) {
      set({ error: error.message, loading: false });
    }
  },
}));

// Caller can properly await
await useStore.getState().fetchData('123');
```

---

## Pattern: Selector Stability

**Problem:** Selectors that create new objects cause unnecessary re-renders.

```typescript
// WRONG - creates new object every render
const data = useStore((state) => ({
  name: state.name,
  count: state.count,
}));

// CORRECT - use multiple selectors
const name = useStore((state) => state.name);
const count = useStore((state) => state.count);

// OR - use shallow comparison (Zustand 4.x)
import { shallow } from 'zustand/shallow';

const { name, count } = useStore(
  (state) => ({ name: state.name, count: state.count }),
  shallow
);

// Zustand 5.x - use useShallow hook
import { useShallow } from 'zustand/react/shallow';

const { name, count } = useStore(
  useShallow((state) => ({ name: state.name, count: state.count }))
);
```

---

## Pattern: Derived State

**Problem:** Computing derived values in selectors vs storing them.

```typescript
const useStore = create((set, get) => ({
  items: [],

  // WRONG - storing derived state that can become stale
  totalItems: 0,
  updateTotalItems: () => {
    set({ totalItems: get().items.length });
  },
}));

// CORRECT - compute in selector (always fresh)
const totalItems = useStore((state) => state.items.length);

// For expensive computations, memoize outside the store
import { useMemo } from 'react';

function Component() {
  const items = useStore((state) => state.items);
  const expensiveResult = useMemo(() => {
    return computeExpensiveAnalysis(items);
  }, [items]);
}
```

---

## Pattern: Store Subscriptions for Side Effects

**Problem:** Need to react to state changes outside React components.

```typescript
// Subscribe to specific state changes
const unsubscribe = useStore.subscribe(
  (state) => state.data,
  (data, prevData) => {
    console.log('Data changed:', { prev: prevData, current: data });
    // Persist to storage, send analytics, etc.
  },
  { equalityFn: shallow }
);

// In Zustand 4.x with subscribeWithSelector middleware
import { subscribeWithSelector } from 'zustand/middleware';

const useStore = create(
  subscribeWithSelector((set, get) => ({
    data: {},
    // ...
  }))
);
```

---

## Pattern: Testing Zustand Stores

**Problem:** Tests need to reset store state and verify async flows.

```typescript
// Store with reset capability
const initialState = {
  data: {},
  loading: false,
};

const useStore = create((set, get) => ({
  ...initialState,

  // Actions...

  // Reset for testing
  _reset: () => set(initialState),
}));

// Test
describe('Data Store', () => {
  beforeEach(() => {
    useStore.getState()._reset();
  });

  it('fetches data correctly', async () => {
    const store = useStore.getState();

    await store.fetchData('123');

    expect(useStore.getState().data).toBeDefined();
    expect(useStore.getState().loading).toBe(false);
  });
});
```

---

## Pattern: Debugging State Changes

**Problem:** Tracking down when/where state changed unexpectedly.

```typescript
// Add logging middleware
import { devtools } from 'zustand/middleware';

const useStore = create(
  devtools(
    (set, get) => ({
      // ... your store
    }),
    { name: 'MyStore' }
  )
);

// Manual logging for specific debugging
const useStore = create((set, get) => ({
  data: {},

  saveData: (id: string, value: number) => {
    console.log('[saveData] Before:', {
      id,
      value,
      currentData: get().data,
    });

    set((state) => ({
      data: { ...state.data, [id]: value },
    }));

    console.log('[saveData] After:', {
      data: get().data,
    });
  },
}));
```

---

## Pattern: Persist Middleware

**Problem:** Persisting state across sessions.

```typescript
import { persist } from 'zustand/middleware';

// Web - localStorage
const useStore = create(
  persist(
    (set, get) => ({
      preferences: {},
      setPreference: (key, value) =>
        set((state) => ({
          preferences: { ...state.preferences, [key]: value }
        })),
    }),
    {
      name: 'app-preferences',
      // Optional: choose what to persist
      partialize: (state) => ({ preferences: state.preferences }),
    }
  )
);
```

---

## Common Pitfalls

| Pitfall | Solution |
|---------|----------|
| Stale closure after await | Use `get()` after every await |
| Selector returns new object | Use `shallow` or multiple selectors |
| Action not awaitable | Add `async` keyword, return promise |
| State seems stale in component | Component hasn't re-rendered yet - use `getState()` for immediate reads |
| Can't find when state changed | Add devtools middleware or manual logging |

---

## Zustand 5.x Migration Notes

If upgrading from 4.x:

```typescript
// 4.x - shallow from main package
import { shallow } from 'zustand/shallow';

// 5.x - useShallow hook for React
import { useShallow } from 'zustand/react/shallow';

// 4.x - type parameter often needed
const useStore = create<StoreType>()((set, get) => ({...}));

// 5.x - improved type inference
const useStore = create((set, get) => ({...}));
```

Attribution

aiskillstoreaiskillstore
View sourceSee grades on GitHubMore from aiskillstore →
SSkills Directory ProSkills Directory

Get any skill into Claude in one click.

Download any skill as a ZIP for Claude.ai, Claude Desktop, or .claude/skills. $9/mo.

See Pro

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

Comments (0)

No comments yet. Be the first to comment!

SSkills Directory ProSkills Directory

Get any skill into Claude in one click.

Download any skill as a ZIP for Claude.ai, Claude Desktop, or .claude/skills. $9/mo.

See Pro

Related Skills

Clean Code

Pragmatic coding standards - concise, direct, no over-engineering, no unnecessary comments

304955 votes

Browser Extension Developer

Use this skill when developing or maintaining browser extension code in the `browser/` directory, including Chrome/Firefox/Edge compatibility, content scripts, background scripts, or i18n updates.

285172 votes

Seo Optimizer

SEO optimization with keyword analysis, readability assessment, technical validation, content quality. Use for search rankings, blog posts, content audits, or encountering keyword density, readability scores, meta tags, schema markup errors.

2222 votes

Google Official Seo Guide

Official Google SEO guide covering search optimization, best practices, Search Console, crawling, indexing, and improving website search visibility based on official Google documentation

1862 votes

Tanstack Start

Build a full-stack TanStack Start app on Cloudflare Workers from scratch — SSR, file-based routing, server functions, D1+Drizzle, better-auth, Tailwind v4+shadcn/ui. Use whenever the user mentions TanStack Start, asks to scaffold a full-stack Cloudflare app with SSR, wants an SSR dashboard, or asks for a React 19 + Cloudflare Workers app with file-based routing and server functions — even if they don't name TanStack Start specifically. No template repo — Claude generates every file fresh per ...

10341 votes
View all in development →