zustand-store-patterns
БесплатноБез исполняемых скриптовНе проверенUse when creating and managing Zustand stores for React state management. Covers store creation, selectors, actions, and basic usage patterns.
от TheBushidoCollective★ 202 звезды на GitHubОб этом скилле
Zustand - Store Patterns
Zustand is a small, fast, and scalable state management solution for React. It uses a simplified flux principles with a hooks-based API.
Key Concepts
Store Creation
A Zustand store is created using the create function:
import { create } from 'zustand'
interface BearStore {
bears: number
increasePopulation: () => void
removeAllBears: () => void
}
const useBearStore = create<BearStore>((set) => ({
bears: 0,
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 }),
}))
Using the Store in Components
function BearCounter() {
const bears = useBearStore((state) => state.bears)
return <h1>{bears} around here...</h1>
}
function Controls() {
const increasePopulation = useBearStore((state) => state.increasePopulation)
return <button onClick={increasePopulation}>Add bear</button>
}
State Updates
Zustand provides two ways to update state:
// Replace state
set({ bears: 5 })
// Merge state (shallow merge)
set((state) => ({ bears: state.bears + 1 }))
Best Practices
1. Use Selectors for Performance
Select only the state you need to prevent unnecessary re-renders:
// ❌ Bad: Component re-renders on any state change
function BadComponent() {
const store = useBearStore()
return <div>{store.bears}</div>
}
// ✅ Good: Component only re-renders when bears changes
function GoodComponent() {
const bears = useBearStore((state) => state.bears)
return <div>{bears}</div>
}
2. Separate Actions from State
Keep your store organized by separating data from actions:
interface TodoStore {
// State
todos: Todo[]
filter: 'all' | 'active' | 'completed'
// Actions
addTodo: (text: string) => void
toggleTodo: (id: string) => void
removeTodo: (id: string) => void
setFilter: (filter: TodoStore['filter']) => void
}
const useTodoStore = create<TodoStore>((set) => ({
todos: [],
filter: 'all',
addTodo: (text) =>
set((state) => ({
todos: [...state.todos, { id: Date.now().toString(), text, completed: false }],
})),
toggleTodo: (id) =>
set((state) => ({
todos: state.todos.map((todo) =>
todo.id === id ? { ...todo, completed: !todo.completed } : todo
),
})),
removeTodo: (id) =>
set((state) => ({
todos: state.todos.filter((todo) => todo.id !== id),
})),
setFilter: (filter) => set({ filter }),
}))
3. Use Shallow Equality for Multiple Selectors
When selecting multiple values, use shallow from zustand/shallow:
import { create } from 'zustand'
import { shallow } from 'zustand/shallow'
const useStore = create<Store>((set) => ({
nuts: 0,
honey: 0,
increaseNuts: () => set((state) => ({ nuts: state.nuts + 1 })),
increaseHoney: () => set((state) => ({ honey: state.honey + 1 })),
}))
// ✅ Using shallow comparison
function Component() {
const { nuts, honey } = useStore(
(state) => ({ nuts: state.nuts, honey: state.honey }),
shallow
)
return <div>{nuts} nuts, {honey} honey</div>
}
4. Organize Large Stores with Slices
For complex applications, split stores into logical slices:
interface UserSlice {
user: User | null
login: (credentials: Credentials) => Promise<void>
logout: () => void
}
interface CartSlice {
items: CartItem[]
addItem: (item: Product) => void
removeItem: (id: string) => void
clearCart: () => void
}
const createUserSlice = (set: StateCreator<UserSlice>) => ({
user: null,
login: async (credentials) => {
const user = await api.login(credentials)
set({ user })
},
logout: () => set({ user: null }),
})
const createCartSlice = (set: StateCreator<CartSlice>) => ({
items: [],
addItem: (product) =>
set((state) => ({
items: [...state.items, { ...product, quantity: 1 }],
})),
removeItem: (id) =>
set((state) => ({
items: state.items.filter((item) => item.id !== id),
})),
clearCart: () => set({ items: [] }),
})
const useStore = create<UserSlice & CartSlice>()((...a) => ({
...createUserSlice(...a),
...createCartSlice(...a),
}))
5. Access Store Outside Components
Use getState and setState for non-reactive access:
const useBearStore = create<BearStore>((set, get) => ({
bears: 0,
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
doSomething: () => {
const currentBears = get().bears
console.log(`Current bears: ${currentBears}`)
},
}))
// Outside components
const currentState = useBearStore.getState()
useBearStore.setState({ bears: 10 })
Examples
Simple Counter Store
import { create } from 'zustand'
interface CounterStore {
count: number
increment: () => void
decrement: () => void
reset: () => void
}
export const useCounterStore = create<CounterStore>((set) => ({
count: 0,
increment: () => s
Установить zustand-store-patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadWriteEditBashGrepGlobFAQ
Что делает скилл zustand-store-patterns?
Use when creating and managing Zustand stores for React state management. Covers store creation, selectors, actions, and basic usage patterns.
Как установить скилл zustand-store-patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл zustand-store-patterns запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic