Command Palette

Search for a command to run...

Назад к скиллам
скилл № 07889

zustand

Zustand is a small state-management library for React: a store is a hook, components subscribe to slices of it with selectors, and no context provider is…

БесплатноБез исполняемых скриптов
TerminalSkillsот TerminalSkills★ 221 звезда на GitHub

Установить zustand в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Об этом скилле

Zustand — Minimal React State Management

Overview

Zustand keeps application state in a store created with create(). The store is a React hook: a component calls it with a selector and re-renders only when the selected value changes. There is no provider to wrap the app in, actions live next to the state they change, and the same store can be read and written from non-React code. Middleware adds persistence, Redux DevTools, Immer-style updates and selector subscriptions.

This skill targets Zustand 5 (current release line 5.0.x). Version 5 dropped default exports, removed the equality-function argument from create, and requires selectors to return stable references.

Instructions

Install

npm install zustand
npm install immer   # only if you use zustand/middleware/immer; it is an optional peer dependency

Create a store

In TypeScript, write create<State>()(...) with the extra pair of parentheses; that form is what lets middleware types compose.

// src/stores/todo-store.ts
import { create } from "zustand";

export interface Todo { id: string; text: string; done: boolean }
export type Filter = "all" | "active" | "done";

interface TodoState {
  todos: Todo[];
  filter: Filter;
  addTodo: (text: string) => void;
  toggleTodo: (id: string) => void;
  setFilter: (filter: Filter) => void;
  fetchTodos: () => Promise<void>;
  reset: () => void;
}

export const useTodoStore = create<TodoState>()((set, get, store) => ({
  todos: [],
  filter: "all",
  addTodo: (text) =>
    set((state) => ({
      todos: [...state.todos, { id: crypto.randomUUID(), text, done: false }],
    })),
  toggleTodo: (id) =>
    set((state) => ({
      todos: state.todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t)),
    })),
  setFilter: (filter) => set({ filter }),      // set() merges one level deep
  fetchTodos: async () => {                    // async actions just call set() when ready
    const response = await fetch("/api/todos");
    set({ todos: await response.json() });
    console.log(`loaded ${get().todos.length} todos`);
  },
  reset: () => set(store.getInitialState()),
}));

set merges only the top level. Nested objects must be copied by hand (or use the immer middleware below). set(newState, true) replaces the whole state instead of merging; in v5 the types require a complete state object when the flag is true.

Read state in components

// src/components/todos.tsx
import { useShallow } from "zustand/react/shallow";
import { useTodoStore } from "../stores/todo-store";

export function TodoCount() {
  // Re-renders only when the selected value changes (strict equality)
  const count = useTodoStore((s) => s.todos.length);
  return <span>{count} todos</span>;
}

export function TodoList() {
  // A selector that builds a new object or array must be wrapped in useShallow
  const { todos, filter, toggleTodo } = useTodoStore(
    useShallow((s) => ({ todos: s.todos, filter: s.filter, toggleTodo: s.toggleTodo })),
  );
  const visible = todos.filter((t) =>
    filter === "all" ? true : filter === "done" ? t.done : !t.done,
  );
  return (
    <ul>
      {visible.map((t) => (
        <li key={t.id} onClick={() => toggleTodo(t.id)}>{t.text}</li>
      ))}
    </ul>
  );
}

Calling the hook with no selector (useTodoStore()) subscribes the component to every change in the store.

Middleware: devtools, persist, immer

Keep devtools outermost: it changes the type of set, and a middleware wrapped around it can lose that change.

// src/stores/settings-store.ts
import { create } from "zustand";
import { devtools, persist, createJSONStorage } from "zustand/middleware";
import { immer } from "zustand/middleware/immer";

interface SettingsState {
  theme: "light" | "dark";
  editor: { fontSize: number; wordWrap: boolean };
  lastSyncError: string | null;
  setFontSize: (size: number) => void;
  toggleTheme: () => void;
}

export const useSettingsStore = create<SettingsState>()(
  devtools(
    persist(
      immer((set) => ({
        theme: "light",
        editor: { fontSize: 14, wordWrap: true },
        lastSyncError: null,
        // immer: mutate the draft; the third argument names the action in Redux DevTools
        setFontSize: (size) =>
          set((state) => { state.editor.fontSize = size; }, undefined, "settings/setFontSize"),
        toggleTheme: () =>
          set((state) => { state.theme = state.theme === "light" ? "dark" : "light"; }),
      })),
      {
        name: "settings-v1",                              // storage key, must be unique
        storage: createJSONStorage(() => localStorage),   // the default, shown for clarity
        partialize: (state) => ({ theme: state.theme, editor: state.editor }),
      },
    ),
    { name: "SettingsStore", enabled: process.env.NODE_ENV !== "production" },
  ),
);

Other persist options: version with migrate(persistedState, version) for schema changes, merge f

Полный SKILL.md на GitHub

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

  • _scores.json

FAQ

Что делает скилл zustand?

Zustand is a small state-management library for React: a store is a hook, components subscribe to slices of it with selectors, and no context provider is needed. Use when a user asks to "add a Zustand store", "share state between components without Redux", "persist state to localStorage", "fix Maximum update depth exceeded after upgrading to Zustand v5", "use Zustand with Next.js", or wants the persist, devtools, immer or subscribeWithSelector middleware. Covers the v5 API: typed stores, useShallow, middleware order, access outside React, and per-request stores.

Как установить скилл zustand?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл zustand запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить zustand с