| Pitfall | Solution | |---------|----------| | Overusing one giant store | Split into slices using composition | | Re-rendering entire component | Use fine-grained selectors | | Storing non-serializable data (Date, Map) | Use JSON serialization or ignore in persist | | Memory leaks in subscriptions | Always unsubscribe in useEffect cleanup | | Async race conditions | Use AbortController or flags | | SSR (Next.js) hydration mismatch | Use persist with skipHydration option | SSR Example with Next.js: // store.js import create from 'zustand' const useStore = create((set) => ( bears: 0, increase: () => set((state) => ( bears: state.bears + 1 )), ))
const useStore = create((...args) => ( ...createUserSlice(...args), ...createCartSlice(...args) )) Zustand’s true strength comes from its middleware ecosystem. 1. Persist Middleware (localStorage) import create from 'zustand' import persist, createJSONStorage from 'zustand/middleware' const useStore = create( persist( (set) => ( theme: 'light', setTheme: (theme) => set( theme ), ), zust4help full
| Feature | Zustand | Redux Toolkit | Context + useReducer | |---------|---------|---------------|----------------------| | Boilerplate | Very low | Medium | High | | Provider required | No | Yes | Yes | | DevTools support | Yes (middleware) | Yes | No | | Async actions | Native | Thunk/Saga | Manual | | Performance | Excellent | Good | Poor (re-renders) | | Learning curve | Minimal | Steep | Moderate | | Bundle size | ~1.5 kB | ~15 kB | ~0 kB (built-in) | Part 8: Real-World Example – Complete E-Commerce Cart import create from 'zustand' import persist from 'zustand/middleware' import shallow from 'zustand/shallow' const useCartStore = create( persist( (set, get) => ( items: [], addItem: (product) => set((state) => const existing = state.items.find((i) => i.id === product.id) if (existing) return items: state.items.map((i) => i.id === product.id ? ...i, quantity: i.quantity + 1 : i ), | Pitfall | Solution | |---------|----------| | Overusing
name: 'app-storage', // unique key in localStorage storage: createJSONStorage(() => localStorage), // use sessionStorage if preferred const unsubscribe = useStore.subscribe( (state) =>
useEffect(() => const unsubscribe = useStore.subscribe( (state) => state.someValue, (value) => console.log(value) ) return unsubscribe , [])
If you searched for "zust4help full" , you likely want —from basic stores to advanced middleware and best practices. This article is that resource.
import useStore from 'zustand' import store from './vanilla-store' function Counter() const count = useStore(store, (state) => state.count) const increment = useStore(store, (state) => state.increment) return <button onClick=increment>count</button>