Catalog My learning Blog
Frontend Developer Course: 100 Concepts in 100 Days · Phase 7 · Lesson 65 · 6 min read

Zustand vs Redux: Global State and Selectors

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: A Cart Store with Selectors and Safe Persistence
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Recognize when an application genuinely needs a global client store, compare Redux Toolkit, Zustand and atom-based libraries, subscribe components to precise slices with selectors to avoid unnecessary re-renders, model updates as actions and keep store state serializable, minimal and free of server data.

Concept Explanation

After moving server data to a query cache, URL state to the URL and local UI state into components, many applications discover they need very little global client state. What remains is state that many distant components read and write and that has no other natural home: a shopping cart before checkout, a multi-panel editor's selection and undo history, a notification queue, a music player's current track, a collaborative canvas's local view. For these, a store, a single object held outside the component tree with subscription support, is the right tool.

The key mechanism that makes stores efficient is the selector. A selector is a function that extracts the part of the store a component needs, such as (state) => state.cart.items.length. The store notifies subscribers on every change, but each component re-renders only if its selected value changed, compared by reference or with a custom equality function. This is the precise subscription that context lacks (Day 57). Selectors must return stable values: a selector that builds a new array or object on every call returns a new reference each time and re-renders on every store change, so derived collections should be memoized or selected as primitive values. React's useSyncExternalStore is the low-level hook that stores use to subscribe safely under concurrent rendering.

The main libraries differ in style. Redux Toolkit organizes state into slices with reducers and actions, uses Immer for immutable updates and comes with powerful DevTools showing every action and state change, plus RTK Query for server state. It suits large teams that value explicit, traceable updates and conventions. Zustand is minimal: a store is a hook created from a function that returns state and actions, with no providers or boilerplate, and it supports selectors and middleware such as persist and devtools. Atom-based libraries such as Jotai and Recoil's successors build state from small independent atoms that components subscribe to individually, which suits fine-grained state graphs.

Good store design follows a few principles regardless of library. Keep state minimal and derive the rest with selectors. Keep it serializable, plain objects and arrays rather than class instances or functions, so it works with DevTools, persistence and server rendering. Model changes as named actions, such as addItem or removeItem, rather than letting components set arbitrary fields, so updates are centralized and testable. Normalize collections that are updated by id into a lookup by id plus an ordered id list. Keep server data out of it.

Persistence deserves care. Persist only an allowlist of non-sensitive fields, version the persisted shape and migrate or discard old versions, validate what you load (Day 45), and reset user-specific state on logout. A store that silently restores yesterday's state for a different user is a privacy bug.

LibraryModelStrengths
Redux ToolkitSlices, actions, reducers with ImmerConventions, DevTools, RTK Query
ZustandHook-based store with actionsMinimal API, no provider, middleware
JotaiIndependent atomsFine-grained subscriptions
Context plus useReducerBuilt inSmall, low-frequency state
SelectorFunction picking a sliceRe-render only when the slice changes
useSyncExternalStoreReact subscription primitiveSafe with concurrent rendering

Worked Example: A Cart Store with Selectors and Safe Persistence

The Zustand store exposes actions, components subscribe through narrow selectors, and only an allowlist of fields is persisted with a version.

TypeScript
import { create } from 'zustand';
import { persist, devtools } from 'zustand/middleware';

type Line = { sku: string; qty: number; unitCents: number };
type CartState = {
  lines: Record<string, Line>;        // normalized by sku
  order: string[];                    // display order
  isDrawerOpen: boolean;              // UI flag, not persisted
  add: (sku: string, unitCents: number) => void;
  setQty: (sku: string, qty: number) => void;
  clear: () => void;
};

export const useCart = create<CartState>()(devtools(persist((set) => ({
  lines: {}, order: [], isDrawerOpen: false,
  add: (sku, unitCents) => set((s) => {
    const line = s.lines[sku];
    return line
      ? { lines: { ...s.lines, [sku]: { ...line, qty: line.qty + 1 } } }
      : { lines: { ...s.lines, [sku]: { sku, qty: 1, unitCents } }, order: [...s.order, sku] };
  }, false, 'cart/add'),
  setQty: (sku, qty) => set((s) => qty <= 0
    ? { lines: Object.fromEntries(Object.entries(s.lines).filter(([k]) => k !== sku)), order: s.order.filter((k) => k !== sku) }
    : { lines: { ...s.lines, [sku]: { ...s.lines[sku], qty } } }, false, 'cart/setQty'),
  clear: () => set({ lines: {}, order: [] }, false, 'cart/clear'),
}), {
  name: 'cart',
  version: 2,
  partialize: (s) => ({ lines: s.lines, order: s.order }),     // allowlist: no UI flags
  migrate: () => ({ lines: {}, order: [] }),                    // drop incompatible old shapes
})));

// Narrow selectors: each component re-renders only for its slice
export const useCartCount = () => useCart((s) => s.order.reduce((n, k) => n + s.lines[k].qty, 0));
export const useCartTotalCents = () => useCart((s) => s.order.reduce((n, k) => n + s.lines[k].qty * s.lines[k].unitCents, 0));
export const useLine = (sku: string) => useCart((s) => s.lines[sku]);   // stable reference until that line changes

function CartBadge() {
  const count = useCartCount();          // number: unaffected by drawer toggles or other lines' objects
  return <span aria-label={`${count} items in cart`}>{count}</span>;
}

Selecting s.order.map(...) to build a new array of lines inside a selector would return a new reference on every store update and re-render the component every time; selecting primitive totals or individual lines avoids that.

Every store change notifies all subscribers, but each component compares the result of its selector with the previous one. The cart badge selects a number and ignores drawer toggles; the drawer selects only its flag.
Every store change notifies all subscribers, but each component compares the result of its selector with the previous one. The cart badge selects a number and ignores drawer toggles; the drawer selects only its flag.

Real-World Examples

  • Redux's style guide recommends normalizing state, keeping it serializable, modeling actions as events and using Redux Toolkit, and Redux DevTools' time-travel debugging depends on state and actions being serializable.
  • Zustand, maintained by the Poimandres collective that also builds Jotai and React Three Fiber, became one of the most downloaded React state libraries by offering selector-based subscriptions with an API small enough to read in a few minutes.
Key TakeawaysAfter moving server, URL, form and local state to their homes, keep a global store only for genuinely shared client state. Subscribe through narrow selectors that return stable values so components re-render only for their slice. Keep store state minimal, serializable, normalized and changed through named actions, persist only an allowlist with versions and migrations, and reset it on logout.

Review Questions & Answers

The store notifies all subscribers on every change, but each component compares the result of its selector with the previous result and re-renders only if it changed. Context, by contrast, re-renders every consumer whenever its value changes, whatever part they use.

Selected values are compared by reference by default. A selector that creates a new array or object each time returns a different reference after every store update, even if the contents are identical, so the component always re-renders. Memoize the result or select primitives or existing references.

Serializable state, plain objects and arrays, works with DevTools inspection and time travel, persistence to storage, server rendering and hydration, and debugging snapshots. Class instances, functions and DOM nodes break these features.

Persist only an allowlist of non-sensitive fields, never tokens or UI flags, version the persisted shape with migrations for changes, validate the loaded data, and clear user-specific state on logout so it never appears for another user.