--- description: This rule file provides definitive guidelines for using Zustand in React applications, focusing on modularity, performance, and maintainability through opinionated best practices and code examples. globs: **/*.{js,jsx,ts,tsx} --- # zustand Best Practices Zustand is our go-to for global state management due to its simplicity and performance. This guide outlines our team's definitive best practices for using Zustand, ensuring consistency, maintainability, and optimal performance across all projects. ## 1. Store Definition & Organization ### 1.1 Modular Slices for Large Stores Split large stores into logical "slices" to keep files focused and maintainable. Combine these slices into a single `create` call. ❌ **BAD: Monolithic Store** ```javascript // src/store/appStore.js import { create } from 'zustand'; export const useAppStore = create((set) => ({ // Auth state token: null, user: null, login: (token, user) => set({ token, user }), logout: () => set({ token: null, user: null }), // UI state isLoading: false, modalOpen: false, setLoading: (loading) => set({ isLoading: loading }), toggleModal: () => set((state) => ({ modalOpen: !state.modalOpen })), // Cart state items: [], addItem: (item) => set((state) => ({ items: [...state.items, item] })), removeItem: (id) => set((state) => ({ items: state.items.filter(i => i.id !== id) })), })); ``` ✅ **GOOD: Sliced Store** ```javascript // src/store/authSlice.js export const createAuthSlice = (set) => ({ token: null, user: null, login: (token, user) => set({ token, user }), logout: () => set({ token: null, user: null }), }); // src/store/uiSlice.js export const createUiSlice = (set) => ({ isLoading: false, modalOpen: false, setLoading: (loading) => set({ isLoading: loading }), toggleModal: () => set((state) => ({ modalOpen: !state.modalOpen })), }); // src/store/index.js import { create } from 'zustand'; import { createAuthSlice } from './authSlice'; import { createUiSlice } from './uiSlice'; export const useAppStore = create((...a) => ({ ...createAuthSlice(...a), ...createUiSlice(...a), })); ``` > **Context:** This pattern scales better, improves type safety, and makes it easier to reason about specific parts of your state. ### 1.2 Naming Conventions & File Layout Name store hooks `use[Feature]Store` and place them in `src/store/[feature]Store.js` (or `.ts/.tsx`). Export only the main hook. ❌ **BAD: Generic Naming & Poor Location** ```javascript // src/components/MyComponent/store.js import { create } from 'zustand'; export const useStore = create(() => ({ /* ... */ })); ``` ✅ **GOOD: Specific Naming & Centralized Location** ```javascript // src/store/cartStore.js import { create } from 'zustand'; export const useCartStore = create((set) => ({ items: [], addItem: (item) => set((state) => ({ items: [...state.items, item] })), })); // src/store/userStore.ts (TypeScript example) import { create } from 'zustand'; interface UserState { id: string | null; name: string | null; fetchUser: () => Promise; } export const useUserStore = create((set) => ({ id: null, name: null, fetchUser: async () => { // ... API call set({ id: '123', name: 'John Doe' }); }, })); ``` > **Context:** This makes stores easily discoverable and prevents naming collisions. ## 2. State Access & Performance ### 2.1 Selective Subscriptions with Selectors Always use selector functions with `useStore` to subscribe only to the specific parts of the state your component needs. This prevents unnecessary re-renders. Use shallow comparison (`shallow`) for objects or arrays if the entire object/array is needed. ❌ **BAD: Subscribing to Entire State** ```javascript // Component re-renders on ANY state change in useCartStore const cart = useCartStore(); console.log(cart.items.length); ``` ✅ **GOOD: Selective Subscription** ```javascript // Component re-renders ONLY when cart.items changes import { shallow } from 'zustand/shallow'; // For primitive values: const itemCount = useCartStore((state) => state.items.length); // For objects/arrays: use shallow comparison const { items, total } = useCartStore( (state) => ({ items: state.items, total: state.total }), shallow // Important for objects/arrays to prevent re-renders on reference changes ); ``` > **Context:** This is the single most important performance optimization in Zustand. Without it, your components will re-render far more often than necessary. ### 2.2 Immutable Updates Always update state immutably. Use the functional `set(state => ...)` form to ensure you're working with the latest state. ❌ **BAD: Direct Mutation** ```javascript // This mutates the state directly, which can lead to bugs and difficult debugging. // Zustand might not detect the change, or other parts of your app might get stale state. const addItem = (item) => set((state) => { state.items.push(item); // ❌ DIRECT MUTATION return state; }); ``` ✅ **GOOD: Functional, Immutable Updates** ```javascript const addItem = (item) => set((state) => ({ items: [...state.items, item], // ✅ Creates a new array })); const updateItemQuantity = (id, quantity) => set((state) => ({ items: state.items.map(item => item.id === id ? { ...item, quantity } : item ), })); ``` > **Context:** Immutability is a core principle of React and state management. It simplifies change detection and prevents subtle bugs. ## 3. Side Effects & Asynchronous Logic ### 3.1 Centralized Async Actions Place API calls and other side effects directly within your store actions. This centralizes data fetching logic and keeps components clean. ❌ **BAD: API Calls in Components** ```javascript // src/components/ProductList.jsx import React, { useEffect } from 'react'; import { useProductStore } from '../../store/productStore'; import api from '../../utils/api'; function ProductList() { const { products, setProducts } = useProductStore(); useEffect(() => { const fetchProducts = async () => { const response = await api.get('/products'); setProducts(response.data); }; fetchProducts(); }, [setProducts]); // ... render products } ``` ✅ **GOOD: Store-Managed Async Actions** ```javascript // src/store/productStore.js import { create } from 'zustand'; import api from '../../utils/api'; export const useProductStore = create((set) => ({ products: [], isLoading: false, error: null, fetchProducts: async () => { set({ isLoading: true, error: null }); try { const response = await api.get('/products'); set({ products: response.data, isLoading: false }); } catch (error) { set({ error: error.message, isLoading: false }); } }, })); // src/components/ProductList.jsx import React, { useEffect } from 'react'; import { useProductStore } from '../../store/productStore'; function ProductList() { const { products, isLoading, error, fetchProducts } = useProductStore( (state) => ({ products: state.products, isLoading: state.isLoading, error: state.error, fetchProducts: state.fetchProducts, }), shallow ); useEffect(() => { fetchProducts(); }, [fetchProducts]); if (isLoading) return
Loading products...
; if (error) return
Error: {error}
; // ... render products } ``` > **Context:** This pattern keeps your components focused on rendering UI and your stores focused on managing data and side effects. ## 4. Middleware Usage ### 4.1 Purposeful & Conditional Middleware Only apply middleware (`devtools`, `persist`, `immer`) where they are genuinely needed. Conditionally enable `devtools` to avoid performance overhead in production. ❌ **BAD: Unnecessary Middleware in Production** ```javascript import { create } from 'zustand'; import { devtools, persist } from 'zustand/middleware'; export const useAuthStore = create( devtools( // Always enabled persist( // Always enabled, even if auth token is short-lived (set) => ({ /* ... */ }), { name: 'auth-storage' } ) ) ); ``` ✅ **GOOD: Conditional Devtools & Targeted Persist** ```javascript import { create } from 'zustand'; import { devtools, persist } from 'zustand/middleware'; // Only enable devtools in development const devtoolsMiddleware = (f) => process.env.NODE_ENV === 'development' ? devtools(f) : f; export const useAuthStore = create( devtoolsMiddleware( // Conditionally enabled persist( // Only persist if truly needed (e.g., user preferences, not sensitive tokens) (set) => ({ token: null, user: null, login: (token, user) => set({ token, user }), logout: () => set({ token: null, user: null }), }), { name: 'auth-storage', // Consider `getStorage: () => sessionStorage` for shorter-lived data // Or don't persist sensitive tokens at all, rely on server-side cookies } ) ) ); // Example for a store that doesn't need persist, but benefits from devtools in dev export const useUiStore = create( devtoolsMiddleware( (set) => ({ modalOpen: false, toggleModal: () => set((state) => ({ modalOpen: !state.modalOpen })), }) ) ); ``` > **Context:** Middleware adds overhead. Be intentional about where and when you use it. `devtools` is invaluable for debugging but should be stripped from production builds. ### 4.2 Immer Middleware for Complex Immutable Updates For deeply nested or complex state updates, use the `immer` middleware to simplify immutable logic. ```javascript // src/store/settingsStore.js import { create } from 'zustand'; import { immer } from 'zustand/middleware/immer'; export const useSettingsStore = create( immer((set) => ({ userSettings: { theme: 'dark', notifications: { email: true, sms: false, }, }, updateTheme: (theme) => set((state) => { state.userSettings.theme = theme; // ✅ Immer allows direct mutation within set }), toggleEmailNotifications: () => set((state) => { state.userSettings.notifications.email = !state.userSettings.notifications.email; }), })) ); ``` > **Context:** Immer makes immutable updates feel like mutable ones, reducing boilerplate and potential errors for complex state structures. Only use it if you find the manual immutable updates cumbersome.