Performance, Memoization and Identity
Build, explain and debug React 19 interfaces: components, rendering, state, effects, identity, forms and actions, server components, concurrency, performance and testing, ending with architecture and typing work on real component challenges.
What you will be able to do
#- Profile a React interaction and identify expensive re-renders.
- Stabilize props with memo, useMemo and useCallback.
- Use children and composition to skip work without memoization.
Overview
#Measure first
Performance work starts with evidence. React DevTools Profiler records an interaction and shows which components rendered, how long they took and why. Optimize the components the profiler flags, not the ones you guess.
memo
memo wraps a component and skips re-rendering it when its props are equal by shallow comparison. It only helps when the parent re-renders often and the child's work is expensive.
const Row = memo(function Row({ item }: { item: Item }) {
return <li>{item.label}</li>;
});
memo is defeated by unstable props. A new object, array or function created during render makes the shallow comparison fail, so the child re-renders anyway.
useMemo and useCallback
useMemo caches a computed value between renders. useCallback caches a function identity. Both take a dependency array and recompute when dependencies change.
const sorted = useMemo(() => [...items].sort(compare), [items]);
const onSelect = useCallback((id: string) => setSelected(id), []);
Do not wrap everything. Memoization has a cost and adds noise. Use it when a computation is measurably expensive or when a stable reference is required to make memo or an effect dependency work correctly.
Composition beats memoization
Passing children from a parent that does not re-render lets a re-rendering wrapper skip work without any memo. The element is created by the outer component, so it is not affected by the inner component's state.
function Layout({ children }: { children: React.ReactNode }) {
const [count, setCount] = useState(0);
return (
<div>
<button onClick={() => setCount((c) => c + 1)}>{count}</button>
{children}
</div>
);
}
Here children is an element created by the parent of Layout, so clicking the button re-renders Layout but not the children.
Keys as a reset tool
Changing a component's key unmounts and remounts it, resetting all state. This is the clean way to reset a form or a widget when an identity changes, instead of writing effects that reset state.
The React Compiler
The React Compiler can insert memoization automatically when it can prove a component is pure. Even with the compiler, understanding identity and purity matters: impure components cannot be safely memoized.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
Does memo prevent Row from re-rendering when Parent updates?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.tsxconst Row = memo(function Row({ item }: { item: Item }) { return <li>{item.label}</li>; }); function Parent() { const [n, setN] = useState(0); const item = { id: 1, label: "a" }; return ( <> <button onClick={() => setN(n + 1)}>{n}</button> <ul><Row item={item} /></ul> </> ); }Exercise 2Implement
Stabilize this component so the memoized Child does not re-render on unrelated parent updates. Fix the object and function props.
starter.tsxfunction Parent() { const [n, setN] = useState(0); return ( <> <button onClick={() => setN(n + 1)}>{n}</button> <Child config={{ size: 10 }} onPick={() => console.log("pick")} /> </> ); }Reveal the reference answer
reference.tsxfunction Parent() { const [n, setN] = useState(0); const config = useMemo(() => ({ size: 10 }), []); const onPick = useCallback(() => console.log("pick"), []); return ( <> <button onClick={() => setN(n + 1)}>{n}</button> <Child config={config} onPick={onPick} /> </> ); }Authored expected output: Child does not re-render when n changes because config and onPick keep stable references.
useMemo holds the object reference and useCallback holds the function reference across renders. With stable props, a memoized Child passes the shallow comparison and skips its render.
Exercise 3Debug
A form resets unexpectedly when the selected record changes. Explain why a key-based reset is better than an effect that resets state.
starter.tsxuseEffect(() => { setDraft(record); }, [record]);Reveal the reference answer
reference.tsxRender the form with key={record.id} so React unmounts the old form and mounts a fresh one with the new initial state. This removes the effect, avoids the extra render that shows the old draft for one frame, and guarantees all form state resets together.Authored expected output: The form shows the new record's values immediately with no stale frame.
An effect that copies props into state runs after commit, so the first render shows stale values. A key change remounts the component, so the first render already uses the new initial state.
Exercise 4Interview
A list of 5000 rows is slow to update when a filter changes. Walk through your optimization approach.
starter.tsx// rows.map((row) => <Row key={row.id} row={row} />)Reveal the reference answer
reference.tsxProfile first to confirm where time goes. If the filtered list is long, virtualize it so only visible rows render. Memoize Row so unchanged rows skip re-rendering. Stabilize the row click handler with useCallback and avoid inline objects. Move the filter computation into useMemo and, if typing is heavy, defer the filter with useDeferredValue. Verify with a second profile and measure the interaction, not just the render count.Authored expected output: A measured, layered plan: virtualize, memoize, stabilize identity, defer, re-measure.
Strong answers measure before optimizing, address the dominant cost (rendering too many rows) before micro-optimizations, and re-measure to prove the improvement.
Common misconceptions
#- memo makes a component never re-render. It skips re-renders only when props are shallow-equal.
- useMemo and useCallback should wrap every value. They add cost and complexity; use them for measured need or identity stability.
- Memoization fixes slow renders caused by too much DOM. Reducing work and list size matters more.
- The React Compiler removes the need to understand identity. Purity and identity still determine correctness.
Follow-up practice
#- react-debugging-and-error-handling
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.