Zustand performance optimization strategies:
-
Selective Subscription
- Only subscribe to the state parts that the component actually needs
- Use callback functions to select state instead of subscribing to the entire state
- Example:
javascript
// Good practice: only subscribe to needed state const count = useStore((state) => state.count); // Avoid: subscribing to entire state const store = useStore(); const count = store.count;
-
Use stable selectors
- Avoid creating new selector functions during component render
- Cache selectors with useCallback or useMemo
- Example:
javascript
import { useCallback } from 'react'; function Counter() { const increment = useCallback( () => useStore.getState().increment(), [] ); const count = useStore((state) => state.count); return ( <div> <h1>{count}</h1> <button onClick={increment}>Increment</button> </div> ); }
-
Batch updates
- Use functional updates with set to batch multiple state changes
- Example:
javascript
const useStore = create((set) => ({ count: 0, user: null, updateData: (newCount, newUser) => set((state) => ({ count: state.count + newCount, user: newUser, })), }));
-
Use middleware
- Proper configuration of persist middleware to avoid over-persistence
- Custom middleware for performance monitoring
-
State structure design
- Organize state structure合理, avoid deep nesting
- Group related state together for easier selective subscription
-
Avoid complex calculations in selectors
- For complex calculations, consider using useMemo or pre-calculating in the store
-
Use getState() and setState()
- For non-React environments or scenarios where re-rendering is not needed
- Example:
javascript
// Use in non-React code const store = useStore.getState(); store.increment();
Performance optimization checklist:
- Use selective subscription instead of full subscription
- Cache selector functions
- Batch state updates
- Design state structure合理
- Avoid complex calculations in selectors
- Use getState() and setState() when appropriate