zustand-advanced-patterns
Use when implementing advanced Zustand patterns including transient updates, subscriptions with selectors, store composition, and performance optimization techniques.
What this skill does
# 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:
```typescript
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:
```typescript
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:
```typescript
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:
```typescript
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>
<button onClick={undo} disabled={!canUndo}>
Undo
</button>
<button onClick={redo} disabled={!canRedo}>
Redo
</button>
{/* Render canvas */}
</div>
)
}
```
### 3. Store Composition
Compose multiple stores together:
```typescript
import { create, StoreApi } from 'zustand'
// Create bound stores that can access each other
function createBoundStore() {
const useAuthStore = create<AuthStore>()((set, get) => ({
user: null,
login: async (credentials) => {
const user = await api.login(credentials)
set({ user })
// Access cart store after login
const cartStore = stores.cart.getState()
await cartStore.syncCart()
},
logout: () => {
set({ user: null })
// Clear cart on logout
stores.cart.getState().clearCart()
},
}))
const useCartStore = create<CartStore>()((set, get) => ({
items: [],
addItem: (item) =>
set((state) => ({ items: [...state.items, item] })),
clearCart: () => set({ items: [] }),
syncCart: async () => {
const user = stores.auth.getState().user
if (!user) return
const items = await api.fetchCart(user.id)
set({ items })
},
}))
return {
auth: useAuthStore,
cart: useCartStore,
}
}
const stores = createBoundStore()
export const useAuthStore = stores.auth
export const useCartStore = stores.cart
```
### 4. React Context Integration
Use Zustand with React Context for scoped stores:
```typescript
import { createContext, useContext, useRef } from 'react'
import { createStore, useStore } from 'zustand'
interface TodoStore {
todos: Todo[]
addTodo: (text: string) => void
toggleTodo: (id: string) => void
}
type TodoStoreApi = ReturnType<typeof createTodoStore>
const createTodoStore = (initialTodos: Todo[] = []) => {
return createStore<TodoStore>()((set) => ({
todos: initialTodos,
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
),
})),
}))
}
const TodoStoreContext = createContext<TodoStoreApi | null>(null)
export function TodoStoreProvider({
children,
initialTodos,
}: {
children: React.ReactNode
initialTodos?: Todo[]
}) {
const storeRef = useRef<TodoStoreApi>()
if (!storeRef.current) {
storeRef.current = createTodoStore(initialTodos)
}
return (
<TodoStoreContext.Provider value={storeRef.current}>
{children}
</TodoStoreContext.Provider>
)
}
export function useTodoStore<T>(selector: (state: TodoStore) => T): T {
const store = useContext(TodoStoreContext)
if (!store) {
throw new Error('useTodoStore must be used within TodoStoreProvider')
}
return useStore(store, selector)
}
// Usage
function Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.