secondsky/claude-skills / plugins/zustand-state-management/skills/zustand-state-management
zustand-state-management
VerifiedZustand state management for React with TypeScript. Use for global state, Redux/Context API migration, localStorage persistence, slices pattern, devtools, Next.js SSR, or encountering hydration errors, TypeScript inference issues, persist middleware problems, infinite render loops.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 9.7 KB |
| assets/example-template.txt | markdown | 416 B |
| references/advanced-topics.md | markdown | 7.9 KB |
| references/common-patterns.md | markdown | 6.4 KB |
| references/example-reference.md | markdown | 760 B |
| references/known-issues.md | markdown | 5.4 KB |
| references/middleware-guide.md | markdown | 5.2 KB |
| references/migration-guide.md | markdown | 6.2 KB |
| references/nextjs-hydration.md | markdown | 5.0 KB |
| references/typescript-patterns.md | markdown | 4.9 KB |
| scripts/check-versions.shexecutable | script | 3.6 KB |
| scripts/example-script.shexecutable | script | 302 B |
| templates/async-actions-store.ts | script | 7.6 KB |
| templates/basic-store.ts | script | 908 B |
| templates/computed-store.ts | script | 5.6 KB |
| templates/devtools-store.ts | script | 3.4 KB |
| templates/nextjs-store.ts | script | 2.6 KB |
| templates/persist-store.ts | script | 2.8 KB |
| templates/slices-pattern.ts | script | 5.0 KB |
| templates/typescript-store.ts | script | 1.8 KB |
templates/computed-store.ts
View on GitHub/**
* Zustand Store with Computed/Derived Values
*
* Use when:
* - Need values calculated from state
* - Want to avoid storing redundant data
* - Need efficient memoization
*
* Pattern: Compute in selectors, not in store
*
* Benefits:
* - Cleaner state (only source data)
* - Automatic recomputation when dependencies change
* - Components only re-render when result changes
*
* Learn more: See SKILL.md Common Patterns section
*/
import { create } from 'zustand'
interface Product {
id: string
name: string
price: number
category: string
inStock: boolean
}
interface CartItem {
productId: string
quantity: number
}
interface ComputedStore {
// Source state (stored)
products: Product[]
cart: CartItem[]
taxRate: number
discountPercent: number
// Actions
addProduct: (product: Product) => void
addToCart: (productId: string, quantity: number) => void
removeFromCart: (productId: string) => void
setTaxRate: (rate: number) => void
setDiscount: (percent: number) => void
}
export const useComputedStore = create<ComputedStore>()((set) => ({
// Initial state
products: [],
cart: [],
taxRate: 0.1, // 10%
discountPercent: 0,
// Actions
addProduct: (product) =>
set((state) => ({
products: [...state.products, product],
})),
addToCart: (productId, quantity) =>
set((state) => {
const existing = state.cart.find((item) => item.productId === productId)
if (existing) {
return {
cart: state.cart.map((item) =>
item.productId === productId
? { ...item, quantity: item.quantity + quantity }
: item
),
}
}
return {
cart: [...state.cart, { productId, quantity }],
}
}),
removeFromCart: (productId) =>
set((state) => ({
cart: state.cart.filter((item) => item.productId !== productId),
})),
setTaxRate: (rate) => set({ taxRate: rate }),
setDiscount: (percent) => set({ discountPercent: percent }),
}))
// ============================================================================
// COMPUTED/DERIVED SELECTORS (put these in separate file for reuse)
// ============================================================================
/**
* Selector: Get cart items with product details
*/
export const selectCartWithDetails = (state: ComputedStore) =>
state.cart.map((item) => {
const product = state.products.find((p) => p.id === item.productId)
return {
...item,
product,
subtotal: product ? product.price * item.quantity : 0,
}
})
/**
* Selector: Calculate subtotal (before tax and discount)
*/
export const selectSubtotal = (state: ComputedStore) =>
state.cart.reduce((sum, item) => {
const product = state.products.find((p) => p.id === item.productId)
return sum + (product ? product.price * item.quantity : 0)
}, 0)
/**
* Selector: Calculate discount amount
*/
export const selectDiscountAmount = (state: ComputedStore) => {
const subtotal = selectSubtotal(state)
return subtotal * (state.discountPercent / 100)
}
/**
* Selector: Calculate tax amount
*/
export const selectTaxAmount = (state: ComputedStore) => {
const subtotal = selectSubtotal(state)
const discountAmount = selectDiscountAmount(state)
const afterDiscount = subtotal - discountAmount
return afterDiscount * state.taxRate
}
/**
* Selector: Calculate final total
*/
export const selectTotal = (state: ComputedStore) => {
const subtotal = selectSubtotal(state)
const discountAmount = selectDiscountAmount(state)
const taxAmount = selectTaxAmount(state)
return subtotal - discountAmount + taxAmount
}
/**
* Selector: Get products by category
*/
export const selectProductsByCategory = (category: string) => (state: ComputedStore) =>
state.products.filter((product) => product.category === category)
/**
* Selector: Get in-stock products only
*/
export const selectInStockProducts = (state: ComputedStore) =>
state.products.filter((product) => product.inStock)
/**
* Selector: Count items in cart
*/
export const selectCartItemCount = (state: ComputedStore) =>
state.cart.reduce((sum, item) => sum + item.quantity, 0)
/**
* Usage in components:
*
* function CartSummary() {
* // Each selector only causes re-render when its result changes
* const subtotal = useComputedStore(selectSubtotal)
* const discount = useComputedStore(selectDiscountAmount)
* const tax = useComputedStore(selectTaxAmount)
* const total = useComputedStore(selectTotal)
* const itemCount = useComputedStore(selectCartItemCount)
*
* return (
* <div>
* <h3>Cart ({itemCount} items)</h3>
* <p>Subtotal: ${subtotal.toFixed(2)}</p>
* <p>Discount: -${discount.toFixed(2)}</p>
* <p>Tax: ${tax.toFixed(2)}</p>
* <h4>Total: ${total.toFixed(2)}</h4>
* </div>
* )
* }
*
* function ProductList() {
* const inStockProducts = useComputedStore(selectInStockProducts)
*
* return (
* <ul>
* {inStockProducts.map((product) => (
* <li key={product.id}>{product.name} - ${product.price}</li>
* ))}
* </ul>
* )
* }
*
* function CategoryFilter() {
* const electronicsProducts = useComputedStore(selectProductsByCategory('electronics'))
*
* return <div>{electronicsProducts.length} electronics</div>
* }
*
* PERFORMANCE TIP:
* For expensive computations, use useMemo in the component:
*
* function ExpensiveComputation() {
* const data = useComputedStore((state) => state.products)
*
* const result = useMemo(() => {
* // Expensive calculation
* return data.map(...).filter(...).reduce(...)
* }, [data])
*
* return <div>{result}</div>
* }
*/
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirements | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |