zustand
Zustand state management for React. Covers stores, actions, and persistence. Use for simple global state management. USE WHEN: user mentions "zustand"…
от claude-dev-suite★ 51 звезда на GitHub
Установить zustand в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
Zustand Core Knowledge
Deep Knowledge: Use
mcp__documentation__fetch_docswith technology:zustandfor comprehensive documentation.
Basic Store
import { create } from 'zustand';
interface CounterStore {
count: number;
increment: () => void;
decrement: () => void;
reset: () => void;
}
const useCounterStore = create<CounterStore>((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
reset: () => set({ count: 0 }),
}));
// Usage
function Counter() {
const { count, increment } = useCounterStore();
return <button onClick={increment}>{count}</button>;
}
Async Actions
interface UserStore {
user: User | null;
loading: boolean;
error: string | null;
fetchUser: (id: string) => Promise<void>;
}
const useUserStore = create<UserStore>((set) => ({
user: null,
loading: false,
error: null,
fetchUser: async (id) => {
set({ loading: true, error: null });
try {
const user = await api.getUser(id);
set({ user, loading: false });
} catch (err) {
set({ error: err.message, loading: false });
}
},
}));
Selectors
// Select specific state (prevents unnecessary re-renders)
const count = useCounterStore((state) => state.count);
const increment = useCounterStore((state) => state.increment);
// Shallow comparison for objects
import { shallow } from 'zustand/shallow';
const { user, loading } = useUserStore(
(state) => ({ user: state.user, loading: state.loading }),
shallow
);
Persist Middleware
import { persist } from 'zustand/middleware';
const useStore = create(
persist<MyStore>(
(set) => ({
// ... state and actions
}),
{
name: 'my-store',
partialize: (state) => ({ count: state.count }), // Only persist count
}
)
);
DevTools
import { devtools } from 'zustand/middleware';
const useStore = create(
devtools<MyStore>((set) => ({
// ... state and actions
}), { name: 'MyStore' })
);
When NOT to Use This Skill
| Scenario | Use Instead |
|---|---|
| Server state management (API data, caching) | tanstack-query or swr |
| Vue 3 applications | pinia |
| Complex async workflows with side effects | redux-toolkit |
| Form state management | React Hook Form or Formik |
| URL-based state (routing) | React Router or Next.js router |
Anti-Patterns
| Anti-Pattern | Why It's Bad | Correct Approach |
|---|---|---|
| Storing server data in Zustand | No cache invalidation, manual refetching | Use TanStack Query or SWR |
| Creating multiple stores for everything | Increases complexity unnecessarily | Use slices or combine related state |
Mutating state without set() |
Breaks reactivity | Always use set() or immer middleware |
| Storing derived state | Duplicates data, sync issues | Use selectors with computation |
| Not using selectors | Unnecessary re-renders | Use atomic selectors for each value |
| Persisting sensitive data unencrypted | Security vulnerability | Encrypt with createJSONStorage custom storage |
| Using stores outside React components | Memory leaks, testing issues | Keep store access in components/hooks |
| Not resetting state on logout | Data leaks between users | Call setState(initialState) or $reset() |
Quick Troubleshooting
| Issue | Cause | Solution |
|---|---|---|
| Component not re-rendering | Not using selector or wrong selector | Use (state) => state.value selector |
| State updates not persisting | Persist middleware not configured | Add persist() middleware with storage |
| "Cannot read property of undefined" | State hydration race condition | Add skipHydration check or loading state |
| Multiple re-renders | Selecting entire state object | Use shallow equality or atomic selectors |
| Tests failing with store state | Store state persists between tests | Reset with setState() in beforeEach() |
| DevTools not working | Middleware order incorrect | Wrap with devtools() as outer middleware |
| Memory leaks | Subscriptions not cleaned up | Use store.subscribe() with cleanup |
| TypeScript errors with middleware | Wrong generic order | Follow create<T>()(middleware(...)) pattern |
Production Readiness
Store Organization
// stores/userStore.ts - Typed store with slices
import { create } from 'zustand';
import { devtools, persist, subscribeWithSelector } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
interface UserState {
user: User | null;
isAuthenticated: boolean;
}
interface UserActions {
setUser: (user: User | null) => void;
logout: () => void;
}
type UserStore = UserState & UserActions;
const initialState: UserState = {
user: null,
isAuthenticated: false,
};
export const useUserStore = create<UserStor
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
- 01
Read - 02
Grep - 03
Glob - 04
Write - 05
Edit
Вложенные файлы
- quick-ref/middleware.md
- quick-ref/patterns.md
FAQ
Что делает скилл zustand?
Zustand state management for React. Covers stores, actions, and persistence. Use for simple global state management. USE WHEN: user mentions "zustand", "global state", "store", asks about "simple state management", "lightweight state", "create store", "persist state", "middleware", "devtools integration" DO NOT USE FOR: server data - use `tanstack-query` or `swr` instead; Vue apps - use `pinia`; complex async workflows - use `redux-toolkit`
Как установить скилл zustand?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл zustand запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
AnthropicCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
discernment-nudge
AnthropicAfter you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
data-consolidate
AnthropicJoins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
inspection-to-capa
AnthropicRuns the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…