State management

One shop, one cart, four ways to keep it. Tap Add and watch the component tree: which boxes pass props along for nothing, and which ones render again.

Level: IntermediateWatch: 8 steps · ~40 secondsSwitch the way, tap AddRecall: 3 questions · 8 cardsCompare 4 waysTSX · Jest

What you'll take away

  • Spot prop drilling, and why state at the top renders the whole tree again
  • Know when a Context is enough, and when its readers render too often
  • Use a store with selectors, so only components whose slice changed render again
  • Leave API data to TanStack Query, and keep only the app's own state in a store

The 1-minute version

Tap a point and the picture below plays that step.

4Compare them all
useStatestate in App, passed down as props
App
Header
List
Cart
Badge
Card ×3
store
TanStack QueryQuery
API
App · useStatecart: 1
App · useStatecart: 1
tap Add → …
Step 1 / 8 · step by step
–rendered again this time
–pass on props they don't use
Appwho holds this state

The picture: the shop on a big phone, every part that renders again outlined in amber. Beside it the component tree as houses: a gold lot is a house that rendered again, a dashed one only passes props along. Outside the tree stand the store, TanStack Query's cache, and the API's tower up the street. React's rules with no memo, not a timing.

Step 4 · Every option at once, on one clock

Compare them all: State management

The same shop screen, three taps on Add, the cart kept a different way in each tile. Count the components that render again and the ones passing on props they don't use.

Taps on Add: 0 / 3
useStatestate in App, passed down as propsre-renders 0 · pass-through 0

Use it when State used by one component or its close children

Skip it when State many parts of the app use: the props go through components that don't use them

A model of React's rules with no memo: React.memo, useMemo or good selectors cut these numbers in any of them. Not a timing. Press any tile to see it large above, with when it fits.

Which one when

StateKeep it in
one component's (a menu open or shut)useState there
a few close components'useState in their parent, or useReducer
app-wide, rarely changing (theme, user)Context
app-wide, changing often (cart, filters)a store: Zustand or Redux Toolkit
the server's (products, orders)TanStack Query

Server state isn't yours

Data from the API has an owner, the server, and your copy goes stale. TanStack Query fetches, caches, refetches and tracks loading and errors. Copying it into a store means doing all that by hand.

In real code

cart.ts
// The cart's logic in one reducer: a plain function of (state, action), the same for useReducer, Context or a store.
export interface Line { id: string; name: string; price: number; qty: number }
export interface CartState { lines: Line[] }
export type CartAction =
  | { type: "add"; item: Omit<Line, "qty"> }
  | { type: "remove"; id: string }
  | { type: "clear" };

export const emptyCart: CartState = { lines: [] };

export function cartReducer(state: CartState, action: CartAction): CartState {
  switch (action.type) {
    case "add": {
      const found = state.lines.find((l) => l.id === action.item.id);
      // A new array and new objects: React (and selectors) see the change by reference.
      return found
        ? { lines: state.lines.map((l) => (l.id === action.item.id ? { ...l, qty: l.qty + 1 } : l)) }
        : { lines: [...state.lines, { ...action.item, qty: 1 }] };
    }
    case "remove":
      return { lines: state.lines.filter((l) => l.id !== action.id) };
    case "clear":
      return emptyCart;
  }
}

export const itemCount = (s: CartState) => s.lines.reduce((n, l) => n + l.qty, 0);
export const total = (s: CartState) => s.lines.reduce((n, l) => n + l.qty * l.price, 0);
Run: tsc with the app's code, then really called by its Jest tests (in Node, not on a phone)

Add, remove, clear in one plain function, the same one every way below uses.

Common questions

Do I need Redux?

Usually not at first. Start with useState where it's used, lift it to a parent when several children need it, use a Context for values that rarely change. When app-wide state changes often, reach for a store like Zustand or Redux Toolkit.

Is Context slow?

Context itself isn't slow, but every reader renders again on each change. If the value changes often and many components read it, the app does more work than it needs to. Split contexts by how often they change, or move busy state to a store.

What's wrong with prop drilling?

Components in between take and pass on props they never use: a change means editing every layer, and they render again too. A layer or two is fine; deeper than that, try a Context or a store.

Zustand or Redux Toolkit?

They work the same way: a store outside React and selectors. Zustand is short with little setup; Redux Toolkit has a clear structure, DevTools and lots of middleware, good for big teams or complex state. Both are in the code below.

Table: which one when

Should data from the API go in the store?

No. It's server state, with staleness, loading, errors and refetching to handle: let TanStack Query look after it. The store keeps only what the app itself owns, like the cart or filters.

Is useReducer better than useState?

Not better, just suited to state with several kinds of change: all the logic sits in one reducer you can test directly. For rendering and passing props, it behaves exactly like useState.

Next lesson

CachingLevel: Basic

TanStack Query is a cache with a freshness time; the Caching lesson shows hits, misses, TTL and clearing on write, on the server side.