zustand-advanced-patterns
БесплатноБез исполняемых скриптовНе проверенUse when implementing advanced Zustand patterns including transient updates, subscriptions with selectors, store composition, and performance optimization…
от TheBushidoCollective★ 202 звезды на GitHubОб этом скилле
Zustand - Advanced Patterns
Advanced techniques and patterns for building complex applications with Zustand, including transient updates, optimistic updates, and sophisticated state management strategies.
Key Concepts
Transient Updates
Update state without triggering re-renders:
const useStore = create((set) => ({
count: 0,
increment: () =>
set((state) => ({ count: state.count + 1 }), false, 'increment'),
}))
// Usage: Update without re-rendering
useStore.setState({ count: 10 }, true) // replace: true, skip re-render
Subscriptions with Selectors
Subscribe to specific slices of state:
const useStore = create<Store>()((set) => ({ /* ... */ }))
// Subscribe only to count changes
const unsubscribe = useStore.subscribe(
(state) => state.count,
(count, prevCount) => {
console.log(`Count changed from ${prevCount} to ${count}`)
},
{
equalityFn: (a, b) => a === b,
fireImmediately: false,
}
)
Best Practices
1. Optimistic Updates
Update UI immediately, then sync with server:
interface TodoStore {
todos: Todo[]
addTodo: (text: string) => Promise<void>
updateTodo: (id: string, text: string) => Promise<void>
deleteTodo: (id: string) => Promise<void>
}
const useTodoStore = create<TodoStore>()((set, get) => ({
todos: [],
addTodo: async (text) => {
const optimisticTodo = {
id: `temp-${Date.now()}`,
text,
completed: false,
}
// Optimistic update
set((state) => ({
todos: [...state.todos, optimisticTodo],
}))
try {
const savedTodo = await api.createTodo({ text })
// Replace optimistic todo with real one
set((state) => ({
todos: state.todos.map((todo) =>
todo.id === optimisticTodo.id ? savedTodo : todo
),
}))
} catch (error) {
// Rollback on error
set((state) => ({
todos: state.todos.filter((todo) => todo.id !== optimisticTodo.id),
}))
throw error
}
},
updateTodo: async (id, text) => {
const previousTodos = get().todos
// Optimistic update
set((state) => ({
todos: state.todos.map((todo) =>
todo.id === id ? { ...todo, text } : todo
),
}))
try {
await api.updateTodo(id, { text })
} catch (error) {
// Rollback on error
set({ todos: previousTodos })
throw error
}
},
deleteTodo: async (id) => {
const previousTodos = get().todos
// Optimistic update
set((state) => ({
todos: state.todos.filter((todo) => todo.id !== id),
}))
try {
await api.deleteTodo(id)
} catch (error) {
// Rollback on error
set({ todos: previousTodos })
throw error
}
},
}))
2. Undo/Redo Pattern
Implement time-travel functionality:
interface HistoryState<T> {
past: T[]
present: T
future: T[]
}
interface HistoryStore<T> {
history: HistoryState<T>
canUndo: boolean
canRedo: boolean
set: (newPresent: T) => void
undo: () => void
redo: () => void
reset: (initialState: T) => void
}
function createHistoryStore<T>(initialState: T) {
return create<HistoryStore<T>>()((set, get) => ({
history: {
past: [],
present: initialState,
future: [],
},
get canUndo() {
return get().history.past.length > 0
},
get canRedo() {
return get().history.future.length > 0
},
set: (newPresent) =>
set((state) => ({
history: {
past: [...state.history.past, state.history.present],
present: newPresent,
future: [],
},
})),
undo: () =>
set((state) => {
if (state.history.past.length === 0) return state
const previous = state.history.past[state.history.past.length - 1]
const newPast = state.history.past.slice(0, -1)
return {
history: {
past: newPast,
present: previous,
future: [state.history.present, ...state.history.future],
},
}
}),
redo: () =>
set((state) => {
if (state.history.future.length === 0) return state
const next = state.history.future[0]
const newFuture = state.history.future.slice(1)
return {
history: {
past: [...state.history.past, state.history.present],
present: next,
future: newFuture,
},
}
}),
reset: (initialState) =>
set({
history: {
past: [],
present: initialState,
future: [],
},
}),
}))
}
// Usage
interface CanvasState {
shapes: Shape[]
selectedId: string | null
}
const useCanvasStore = createHistoryStore<CanvasState>({
shapes: [],
selectedId: null,
})
function Canvas() {
const { present } = useCanvasStore((state) => state.history)
const { canUndo, canRedo, undo, redo } = useCanvasStore()
return (
<div>
Установить zustand-advanced-patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadWriteEditBashGrepGlobFAQ
Что делает скилл zustand-advanced-patterns?
Use when implementing advanced Zustand patterns including transient updates, subscriptions with selectors, store composition, and performance optimization techniques.
Как установить скилл zustand-advanced-patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл zustand-advanced-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