Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Part 12 / Topic 4 of 6

useCallback: the stable reference memo actually needs

A function prop breaks memo's comparison the moment it is written inline, because an arrow function literal is a brand-new object every single render - never === to the one before it, no matter how identical its behavior. examples/04_usecallback_for_memoized_children.jsx proves this with three parallel lists of the same 50 rows:

// examples/04_usecallback_for_memoized_children.jsx
export function OrderDashboard() {
  const [note, setNote] = useState("");
  const [, setSelectedId] = useState(null);

  const selectInline = (id) => setSelectedId(id);               // new function every render
  const selectStable = useCallback((id) => setSelectedId(id), []); // same function every render

  return (
    <div>
      <input aria-label="dashboard note" value={note} onChange={(e) => setNote(e.target.value)} />
      <ul>{ORDERS.map((o) => <OrderRowImpl key={o.id} order={o} onSelect={selectInline} countKey="unmemoized" />)}</ul>
      <ul>{ORDERS.map((o) => <MemoOrderRow key={o.id} order={o} onSelect={selectInline} countKey="memoizedWithInlineCallback" />)}</ul>
      <ul>{ORDERS.map((o) => <MemoOrderRow key={o.id} order={o} onSelect={selectStable} countKey="memoizedWithStableCallback" />)}</ul>
    </div>
  );
}

Typing into the dashboard note really re-renders both the unmemoized rows and the memoized-with-inline-callback rows on every keystroke - identical counts, because memo on the second list never found a single prop it could call unchanged (onSelect is new every time). The memoized-with-stable-callback rows really stay at their mount-time render count the entire time (examples/04_usecallback_for_memoized_children.test.jsx) - useCallback's stable reference is what finally gave memo something real to skip on. Wrapping a component in memo and leaving its callback props inline, as the second list shows, buys nothing at all.

Done here? The practice set for Part 12 — including the solutions — is on the part page.

Search the guide