zustand

$npx mdskill add compozy/agh/zustand

Implement Zustand stores for shared client state management.

  • Creates domain-specific stores for shared UI state.
  • Uses Zustand with devtools, persist, and immer middleware.
  • Recommends patterns based on store domain and complexity.
  • Provides typed selector hooks and store organization examples.

SKILL.md

.github/skills/zustandView on GitHub ↗
---
name: zustand
description: Expert guide for Zustand state management patterns, store organization, and best practices. Use when implementing client state management with Zustand, creating stores, or managing shared UI state across components.
allowed-tools: Read, Grep, Glob
---

# Zustand State Management Guide

This skill provides guidelines, patterns, and best practices for working with Zustand in this project.

## Quick Start

For detailed store patterns, middleware usage, and comprehensive examples, please refer to `references/patterns.md`.

## Core Philosophy

- **Shared Client State Only**: Use Zustand for shared client state, not server state (use TanStack Query for that).
- **Domain-Specific Stores**: Keep stores focused on specific domains.
- **Type Safety**: Leverage TypeScript for fully typed stores.
- **Simplicity**: Prefer simplicity over complex abstractions.

## Store Organization

### Essential Patterns

- Create separate stores for different domains
- Use slices pattern for large stores
- Keep stores close to features that use them
- Export typed selector hooks for better DX and performance

### Recommended Middleware Stack

Use the following middleware combination for production stores:

```typescript
import { create } from "zustand";
import { devtools, persist } from "zustand/middleware";
import { immer } from "zustand/middleware/immer";

export const useExampleStore = create<ExampleState>()(
  devtools(
    persist(
      immer((set, get) => ({
        // state and actions
      })),
      { name: "example-storage" }
    ),
    { name: "example-store" }
  )
);
```

### Store Structure Template

```typescript
interface StoreState {
  // State properties
  data: DataType | null;
  isLoading: boolean;
  // Group actions together
  actions: {
    fetchData: () => Promise<void>;
    updateData: (updates: Partial<DataType>) => void;
    reset: () => void;
  };
}
```

### Selector Hooks Pattern

Always create selector hooks for performance optimization:

```typescript
// Bad - subscribes to entire store
const { user, isLoading } = useAuthStore();

// Good - subscribes only to specific slices
export const useUser = () => useAuthStore((state) => state.user);
export const useIsLoading = () => useAuthStore((state) => state.isLoading);
export const useAuthActions = () => useAuthStore((state) => state.actions);
```

## Best Practices

1. **Keep stores focused** on specific domains
2. **Use TypeScript** for full type safety
3. **Leverage middleware** for common patterns (devtools, persist, immer)
4. **Create selector hooks** for performance
5. **Use immer** for complex nested state updates
6. **Persist only necessary state** - use `partialize` option
7. **Test stores thoroughly**
8. **Handle async operations properly** with loading/error states
9. **Implement optimistic updates** when appropriate
10. **Document store structure** and actions

## Common Tasks

### Creating a New Store

1. Define the state interface with typed actions
2. Create the store with appropriate middleware
3. Export selector hooks for each state slice
4. Add to the feature's barrel export

### Persisting State

Use the `persist` middleware with `partialize` to persist only necessary data:

```typescript
persist(
  (set) => ({ /* ... */ }),
  {
    name: "store-key",
    partialize: (state) => ({
      // Only persist these fields
      user: state.user,
      preferences: state.preferences,
    }),
  }
);
```

### Using Immer for Updates

Immer allows mutable-style updates that produce immutable state:

```typescript
immer((set) => ({
  updateNested: (id, value) => {
    set((state) => {
      const item = state.items.find((i) => i.id === id);
      if (item) {
        item.value = value; // Mutable style, but produces immutable state
      }
    });
  },
}));
```

## Validation Checklist

Before finishing a task involving Zustand:

- [ ] Store is domain-specific and focused
- [ ] TypeScript interfaces are properly defined
- [ ] Middleware is applied in correct order (devtools > persist > immer)
- [ ] Selector hooks are created for performance
- [ ] Actions are grouped in an `actions` object
- [ ] Only necessary state is persisted
- [ ] Run type checks (`pnpm run typecheck`) and tests (`pnpm run test`)

For detailed rules, examples, and anti-patterns, please consult `references/patterns.md`.

More from compozy/agh

SkillDescription
agent-exploration>-
aghAGH runtime and contribution guide. Use for sessions, agents, native tools, skills, memory, network, tasks, capabilities, bundles, QA, docs, and repo work. Do not use for unrelated projects.
agh-cleanup-failure-paths>-
agh-code-guidelines>-
agh-contract-codegen-coshipContract co-ship for AGH wire changes. Use when editing public DTOs, OpenAPI, JSON-RPC extension shapes, generated clients, or handler request/response semantics. Do not use for internal Go refactors or test-only changes that leave the wire contract unchanged.
agh-data-boundariesData-boundary audit for AGH route loaders, TanStack Query caches, paginated catalogs, filters, ordering, totals, live streams, workspace-scoped reads, and their backend APIs. Use when adding, changing, or debugging those paths. Don't use for presentational-only UI or backend work with no public read-model impact.
agh-designAGH visual-design authority for production UI, static artifacts, prototypes, and reviews. Use when creating or reviewing an AGH surface or changing tokens, typography, spacing, depth, icons, or motion. Do not use for capture-only verification; use agh-ui-screenshot.
agh-qa-bootstrapBootstraps isolated AGH QA labs and emits the canonical manifest for downstream QA. Use when local QA needs daemon, workspace, provider, or playbook setup. Do not use for unit tests, planning-only work, or browser-only checks.
agh-schema-migrationAuthors append-only Goose SQL migrations for AGH SQLite streams and keeps declarative schema sources, atlas.sum, Atlas checks, sqlc output, and migration tests synchronized. Use for SQLite table, column, index, constraint, trigger, or seed-data changes under internal/store or internal/memory. Do not use for in-memory structures, derived Markdown memory, or non-SQLite caches.
agh-test-conventions>-