Basic steps for Zustand state management:
-
Install Zustand
bashnpm install zustand # or yarn add zustand -
Create a Store
javascriptimport { create } from 'zustand'; const useStore = create((set) => ({ count: 0, increment: () => set((state) => ({ count: state.count + 1 })), decrement: () => set((state) => ({ count: state.count - 1 })), reset: () => set({ count: 0 }), })); -
Use in Components
javascriptimport { useStore } from './store'; function Counter() { const count = useStore((state) => state.count); const increment = useStore((state) => state.increment); const decrement = useStore((state) => state.decrement); const reset = useStore((state) => state.reset); return ( <div> <h1>Count: {count}</h1> <button onClick={increment}>Increment</button> <button onClick={decrement}>Decrement</button> <button onClick={reset}>Reset</button> </div> ); } -
Selective Subscription
- Subscribe only to the needed state parts to avoid unnecessary re-renders
- Use callback functions to select specific state properties
-
State Updates
- Use the
setfunction to update state - Support functional updates (receives current state and returns new state)
- Can batch update multiple states
- Use the
Best Practices:
- Organize multiple stores by functional modules
- Use middleware to enhance functionality
- Optimize performance with selective subscription
- Combine with TypeScript for improved type safety