Zustand
Zustand is a small, hook based global store with no Provider. Components subscribe to just the slice of state they need through selectors, so only components whose selected value changed re-render; the persist middleware keeps state across refreshes.
47.1 Why is it used?
- A Context value is one object: when any part changes, every consumer re-renders.
- Changing only the coupon re-renders Header even though the cart count is still 0.
- Every new shared value needs another Provider to wrap.
- We want a store where each component subscribes to only its part.
React (JSX)
// value given by CartProviderconst value = { items, coupon, setCoupon }; function Header() { const { items } = useContext(CartContext); console.log("Header render"); return <h1>Cart: {items.length}</h1>;} function CouponBox() { const cart = useContext(CartContext); const apply = () => cart.setCoupon("DIWALI"); return <button onClick={apply}>Apply</button>;}Output
-- initial --# Cart: 0[button] ApplyConsole: Header render -- after clicking Apply --# Cart: 0[button] ApplyConsole: Header render, Header render- Step 1
1.CouponBox calls setCoupon("DIWALI")
- Step 2
2.Provider creates a new context value object
- Step 3
3.Every useContext(CartContext) consumer re-renders
- Step 4
4.Header re-renders with the same count (0)
47.2 Creating a store with create
- create(fn) receives a set helper; the object it returns is the whole store.
- Data (items, coupon) and actions (addItem, setCoupon, clear) live side by side.
- create returns a React hook, here named useCart.
- The store lives outside React like a normal JS object, so no Provider is needed.
Terminal
npm install zustandJavaScript
import { create } from "zustand"; export const useCart = create((set) => ({ items: [], coupon: "", addItem: (item) => set((state) => ({ items: [...state.items, item], })), setCoupon: (code) => set({ coupon: code }), clear: () => set({ items: [] }),}));47.3 How set works
- set((state) => ({ items: [...state.items, item] })): an updater function, like the useState updater.
- set({ coupon: code }): a plain object is merged into the existing state, so other fields (items) are kept.
- Only top-level merge: nested objects still need to be copied by you.
47.4 Selectors in components
- useCart(s => s.items.length): the selector picks only what the component needs.
- useCart(s => s.addItem) takes just the action.
- Clicking Add updates the store and Header shows Cart: 1, with no Provider.
React (JSX)
import { useCart } from "./store"; function Header() { const count = useCart(s => s.items.length); console.log("Header render"); return <h1>Cart: {count}</h1>;} function AddButton({ product }) { const addItem = useCart(s => s.addItem); const add = () => addItem(product); return <button onClick={add}>Add</button>;}Output
-- initial --# Cart: 0[button] Add -- after clicking Add --# Cart: 1[button] Add- Step 1
1.An action calls set: store state updates
- Step 2
2.Zustand runs every subscribed selector again
- Step 3
3.Compares new result with the previous one (Object.is)
- Step 4
4.Only components whose result changed re-render
Same result = no re-render
47.5 Checkpoint: will Header re-render?
- Header selects items.length, CouponBox selects setCoupon. Click Apply.
- Answer: no. The coupon changed but Header's selector still returns 0, so Header render is logged only once: the opposite of the Context example.
React (JSX)
import { useCart } from "./store"; function Header() { const count = useCart(s => s.items.length); console.log("Header render"); return <h1>Cart: {count}</h1>;} function CouponBox() { const setCoupon = useCart(s => s.setCoupon); const apply = () => setCoupon("DIWALI"); return <button onClick={apply}>Apply</button>;}Output
-- initial render --> Header render -- after clicking Apply --> Header renderScreen: Apply clicked, Cart: 047.6 Persist: the cart survives a refresh
- Without it, a refresh empties the cart.
- Wrap the store function in persist from zustand/middleware.
- name: "cart" is the localStorage key; every update is saved there as JSON.
- After a refresh the store rehydrates from localStorage by itself, so the screen still shows Cart: 2.
JavaScript
import { create } from "zustand";import { persist } from "zustand/middleware"; export const useCart = create( persist( (set) => ({ items: [], addItem: (item) => set((s) => ({ items: [...s.items, item], })), }), { name: "cart" } ));Output
-- after adding 2 items (localStorage "cart") --# Cart: 2Console: {"state":{"items":[...]},"version":0} -- after refresh --# Cart: 247.7 Comparison: Context vs Zustand vs Redux Toolkit
| Point | Context | Zustand | Redux Toolkit |
|---|---|---|---|
| Provider needed | Yes, one per context | No | Yes, one <Provider store> |
| Re-renders | Every consumer on any change | Only components whose selector result changed | Only components whose useSelector result changed |
| Boilerplate | Low | Very low | More (slices, store, typed hooks) |
| Extras | None | Middleware: persist, devtools | DevTools, thunks, strict structure |
| Best for | Rarely changing values (theme) | Shared client state in most apps | Big team projects needing strict structure |
47.8 Common mistakes
- Zustand v5: a selector that returns a new object every call ({ items, addItem }) looks "changed" every time, causing Maximum update depth exceeded.
- Fix: wrap it in useShallow, or write one selector per value.
- Using useCart() with no selector: subscribes to the whole store, re-render on every change.
- Myth: everything goes in the store. Local UI state stays in useState; server data goes to TanStack Query.
React (JSX)
const { items, addItem } = useCart(s => ({ items: s.items, addItem: s.addItem,}));React (JSX)
const { items, addItem } = useCart( useShallow(s => ({ items: s.items, addItem: s.addItem, })));47.9 Best practices
- Always use a selector.
- Keep actions inside the store; outside React (e.g. in an API file) use useCart.getState().
- Multiple values from one selector: useShallow.
- Use partialize in persist to save only the fields you need.
47.10 Interview tips
- Zustand is a small hook based state library with no Provider.
- Selectors subscribe a component to just its part, so only changed ones re-render; with Context every consumer re-renders.
- Compared to Redux Toolkit: much less boilerplate, extras via middleware (persist, devtools).
- Big project needing strict structure: Redux Toolkit; otherwise Zustand is a simple choice.