zustand
Zustand state management patterns including store creation, middleware, persistence, slices, and DevTools integration.
What this skill does
# Zustand Skill
Expert assistance for implementing Zustand state management with modern patterns and TypeScript.
## Capabilities
- Create type-safe Zustand stores
- Implement middleware (persist, devtools, immer)
- Design store slices for modular state
- Optimize selectors for performance
- Handle async actions and subscriptions
- Integrate with React components efficiently
## Usage
Invoke this skill when you need to:
- Set up lightweight global state
- Create stores with persistence
- Implement complex state with slices
- Optimize component re-renders with selectors
- Migrate from Redux or Context
## Inputs
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| storeName | string | Yes | Name of the store |
| stateShape | object | Yes | Initial state structure |
| actions | array | Yes | Store actions to create |
| middleware | array | No | Middleware to apply |
| persist | boolean | No | Enable persistence |
### Configuration Example
```json
{
"storeName": "useCartStore",
"stateShape": {
"items": [],
"total": 0
},
"actions": ["addItem", "removeItem", "clearCart"],
"middleware": ["devtools", "persist"],
"persist": true
}
```
## Generated Patterns
### Basic Store
```typescript
import { create } from 'zustand';
interface CartItem {
id: string;
name: string;
price: number;
quantity: number;
}
interface CartStore {
items: CartItem[];
total: number;
addItem: (item: Omit<CartItem, 'quantity'>) => void;
removeItem: (id: string) => void;
updateQuantity: (id: string, quantity: number) => void;
clearCart: () => void;
}
export const useCartStore = create<CartStore>((set, get) => ({
items: [],
total: 0,
addItem: (item) =>
set((state) => {
const existingItem = state.items.find((i) => i.id === item.id);
if (existingItem) {
return {
items: state.items.map((i) =>
i.id === item.id ? { ...i, quantity: i.quantity + 1 } : i
),
total: state.total + item.price,
};
}
return {
items: [...state.items, { ...item, quantity: 1 }],
total: state.total + item.price,
};
}),
removeItem: (id) =>
set((state) => {
const item = state.items.find((i) => i.id === id);
return {
items: state.items.filter((i) => i.id !== id),
total: state.total - (item ? item.price * item.quantity : 0),
};
}),
updateQuantity: (id, quantity) =>
set((state) => {
const item = state.items.find((i) => i.id === id);
if (!item) return state;
const diff = (quantity - item.quantity) * item.price;
return {
items: state.items.map((i) =>
i.id === id ? { ...i, quantity } : i
),
total: state.total + diff,
};
}),
clearCart: () => set({ items: [], total: 0 }),
}));
```
### Store with Middleware
```typescript
import { create } from 'zustand';
import { devtools, persist, subscribeWithSelector } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
interface UserStore {
user: User | null;
preferences: Preferences;
setUser: (user: User) => void;
updatePreferences: (prefs: Partial<Preferences>) => void;
logout: () => void;
}
export const useUserStore = create<UserStore>()(
devtools(
persist(
subscribeWithSelector(
immer((set) => ({
user: null,
preferences: { theme: 'light', notifications: true },
setUser: (user) =>
set((state) => {
state.user = user;
}),
updatePreferences: (prefs) =>
set((state) => {
Object.assign(state.preferences, prefs);
}),
logout: () =>
set((state) => {
state.user = null;
}),
}))
),
{
name: 'user-storage',
partialize: (state) => ({ preferences: state.preferences }),
}
),
{ name: 'UserStore' }
)
);
```
### Slice Pattern
```typescript
import { create, StateCreator } from 'zustand';
interface AuthSlice {
isAuthenticated: boolean;
token: string | null;
login: (token: string) => void;
logout: () => void;
}
interface UISlice {
sidebarOpen: boolean;
theme: 'light' | 'dark';
toggleSidebar: () => void;
setTheme: (theme: 'light' | 'dark') => void;
}
type StoreState = AuthSlice & UISlice;
const createAuthSlice: StateCreator<StoreState, [], [], AuthSlice> = (set) => ({
isAuthenticated: false,
token: null,
login: (token) => set({ isAuthenticated: true, token }),
logout: () => set({ isAuthenticated: false, token: null }),
});
const createUISlice: StateCreator<StoreState, [], [], UISlice> = (set) => ({
sidebarOpen: true,
theme: 'light',
toggleSidebar: () => set((state) => ({ sidebarOpen: !state.sidebarOpen })),
setTheme: (theme) => set({ theme }),
});
export const useAppStore = create<StoreState>()((...a) => ({
...createAuthSlice(...a),
...createUISlice(...a),
}));
```
### Async Actions
```typescript
import { create } from 'zustand';
interface DataStore {
data: Item[];
loading: boolean;
error: string | null;
fetchData: () => Promise<void>;
}
export const useDataStore = create<DataStore>((set, get) => ({
data: [],
loading: false,
error: null,
fetchData: async () => {
set({ loading: true, error: null });
try {
const response = await fetch('/api/data');
const data = await response.json();
set({ data, loading: false });
} catch (error) {
set({ error: (error as Error).message, loading: false });
}
},
}));
```
## Selector Patterns
```typescript
// Shallow comparison for object selectors
import { shallow } from 'zustand/shallow';
const { items, total } = useCartStore(
(state) => ({ items: state.items, total: state.total }),
shallow
);
// Computed selectors
const itemCount = useCartStore((state) =>
state.items.reduce((sum, item) => sum + item.quantity, 0)
);
```
## Best Practices
- Use selectors to minimize re-renders
- Apply persist middleware for state that should survive refreshes
- Use immer for complex nested updates
- Split large stores into slices
- Keep actions colocated with state
## Target Processes
- react-application-development
- state-management-setup
- nextjs-full-stack
- t3-stack-development
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.