Courses / React 19: From Components to Production / Chapter 29
Module 12 · Practice and Mock Interview · Chapter 29 of 30
Render and Hook Puzzles: Predict the Output
Builds on State and Effects: useState, Events, useEffect and Cleanup, New in React 19: Actions, use, Optimistic UI and ref as a Prop, Advanced Hooks: Refs, Reducers, Context, Layout Effects and Custom Hooks, Concurrent Rendering: Transitions, Deferred Values and Priorities, Rendering Internals and Performance: Fiber, Memo and the Compiler and Suspense, Streaming SSR and Code-Splitting. Next up: Mock Interview: Timed React Prompts With Model Answers.
Part 1 · Renders and batching
How to use these puzzles
A puzzle gives you a small component and an action, and asks what the console shows. Predict first, with a pen if it helps, then open the answer. Every answer is the printed log of a real run on React 19.3.1 under Vitest and jsdom, with StrictMode off unless the puzzle says it is on. Nothing here depends on the browser's paint, so the logs are repeatable, except where a puzzle says its numbers vary.
To predict well, keep three facts in mind. A render is a call to your component function, and it happens before React updates the page. State is a snapshot: inside one render, a state variable never changes. Updates requested in one event handler are batched into one render. The earlier chapters on state and effects teach these in detail, and the puzzles test whether they have become habits.
Puzzle 1. A button handler calls two setters, one for a and one for b. The user clicks once. What is logged after the click?
function TwoSetters() { const [a, setA] = useState(0) const [b, setB] = useState(0) console.log('P1 render', a, b) return ( <button onClick={() => { setA(a + 1) setB(b + 1) }} > go </button> ) }
Puzzle 1: what does one click log?
P1 render 1 1, and nothing else.- Both setters belong to one handler, so React batches them into one render in which both values are 1. The initial render,
P1 render 0 0, came before the click.
Puzzle 2. The handler calls setN(5) whatever the current value. The component renders at 0, and the user clicks three times. After which clicks does the component function run?
function SameValue() { const [n, setN] = useState(0) console.log('P2 render', n) return <button onClick={() => setN(5)}>set 5</button> }
Puzzle 2: which clicks log a render?
- The first click:
P2 render 5, because 0 changed to 5.
Who renders when a parent does
Puzzle 3. Counter holds a number and renders a button, a Child created inside Counter, and whatever children it was given. A parent outside Counter passed in <Child label="children" />. After the first render the user clicks the button once. Which components log?
function Child({ label }: { label: string }) { console.log('P3 render Child', label) return <p>{label}</p> } function Counter({ children }: { children?: ReactNode }) { const [n, setN] = useState(0) console.log('P3 render Counter', n) return ( <> <button onClick={() => setN(n + 1)}>count {n}</button> {children} <Child label="inside" /> </> ) }
Puzzle 3: what is logged after the click?
P3 render Counter 1andP3 render Child inside.- The child named
childrendid not render. Its element was created by the parent outsideCounter, which did not re-render, so React received the same element as before and skipped it. TheChildcreated insideCounteris a new element on every render, so it rendered again.
Puzzle 3, replayed
Watch for which Child is skipped when Counter re-renders
Read it as steps
Only the elements created by the component that re-rendered run again
The scene follows the answer. State changed in Counter, so React called Counter. It then compared each child element with the one from the last render. The one handed down from outside was the identical object, which is a cheap bailout without memo. This is why moving slow parts into a children prop is a standard first fix for a slow screen, as the rendering chapter shows.
Loops and a way out of batching
Puzzle 4. One click runs two loops. The first calls setN(n + 1) three times and the second calls setM((x) => x + 1) three times. Both start at 0, and the component shows n and m. What does it show after one click?
function Loop() { const [n, setN] = useState(0) const [m, setM] = useState(0) return ( <> <button onClick={() => { for (let i = 0; i < 3; i++) setN(n + 1) for (let i = 0; i < 3; i++) setM((x) => x + 1) }} > loop </button> <output> {n} {m} </output> </> ) }
Puzzle 4: what is shown?
1 3.- The first loop uses the snapshot
n, which is 0 each time, so it asks for 1 three times. The second loop queues three updater functions, and each starts from the previous result, so it reaches 3. The run printedP4 1 3.
Puzzle 5. Batching can be switched off for one update with flushSync from react-dom. The handler calls flushSync(() => setA(a + 1)) and then setB(b + 1). How many renders follow one click, and with what values?
function Flush() { const [a, setA] = useState(0) const [b, setB] = useState(0) console.log('P5 render', a, b) return ( <button onClick={() => { flushSync(() => setA(a + 1)) setB(b + 1) }} > flush </button> ) }
Puzzle 5: what is logged after the click?
P5 render 1 0and thenP5 render 1 1.flushSyncforces React to render that update at once, before the handler continues. The second setter then causes its own render. UseflushSyncrarely: it exists for cases such as reading the DOM right after an update.
Check your understanding
Why did Puzzle 3's passed child skip while the inside child rendered?
- The skipped child's element came from a parent that did not render, so React saw the same element object. The inside child's element was created fresh in
Counter's render.
A handler calls setCount(count + 1) three times. Another calls setCount((c) => c + 1) three times. By how much does each grow the count?
- The first by 1, the second by 3.
What does flushSync change about batching?
- It makes React render the wrapped update immediately, so the handler's later updates cause a separate render.
Part 2 · Effects and StrictMode
Order of effects, and a state set inside one
Effects run after React has updated the page, and they run in a fixed order. These puzzles check that order and the cost of an effect that never cleans up.
Puzzle 1. Parent renders Child. Each logs once while rendering and once from an effect that runs on mount. Which order do the four lines appear in?
function Child() { console.log('P1 render Child') useEffect(() => { console.log('P1 effect Child') }, []) return <p>child</p> } function Parent() { console.log('P1 render Parent') useEffect(() => { console.log('P1 effect Parent') }, []) return <Child /> }
Puzzle 1: what is the order?
P1 render Parent,P1 render Child,P1 effect Child,P1 effect Parent.- Rendering goes from the top down, because a parent must render to create its child. Effects run from the bottom up, children first.
Puzzle 2. A component sets ready to true in an effect that runs on mount, and logs on every render. How many render lines appear, and what does each show?
function Mounted() { const [ready, setReady] = useState(false) console.log('P2 render, ready =', ready) useEffect(() => { console.log('P2 effect') setReady(true) }, []) return <p>{ready ? 'ready' : 'waiting'}</p> }
Puzzle 2: what is logged?
P2 render, ready = false, thenP2 effect, thenP2 render, ready = true.- The effect runs after the first render, sets state, and causes a second render. The first render can be on screen briefly with the wrong value. This is the cost that makes setting state in an effect something to avoid.
Dependencies and layout effects
Puzzle 3. An effect logs a and b and has [a] as its dependency list. The component has two buttons that add one to a and to b. The user clicks the b button, then the a button. When does the effect run, and what does it print?
function Deps() { const [a, setA] = useState(0) const [b, setB] = useState(0) useEffect(() => { console.log('P3 effect, a =', a, 'b =', b) }, [a]) return ( <> <button onClick={() => setA(a + 1)}>a</button> <button onClick={() => setB(b + 1)}>b</button> </> ) }
Puzzle 3: what is logged?
P3 effect, a = 0 b = 0on mount, nothing after thebclick, andP3 effect, a = 1 b = 1after theaclick.- The effect re-runs only when a listed dependency changes. When it did run, it read the current
b, which had already moved to 1. Leavingbout of the list is what the lint rulereact-hooks/exhaustive-depswarns about, because the effect uses a value it does not list.
Puzzle 4. A component has a layout effect and a passive effect, both depending on n. Each logs setup and cleanup. After the first render, the user clicks once. What is the order of the lines for the mount, then the click, then the final unmount?
function Both() { const [n, setN] = useState(0) useLayoutEffect(() => { console.log('P4 layout setup', n) return () => console.log('P4 layout cleanup', n) }, [n]) useEffect(() => { console.log('P4 passive setup', n) return () => console.log('P4 passive cleanup', n) }, [n]) return <button onClick={() => setN(n + 1)}>go</button> }
Puzzle 4: what is the order?
- Mount:
layout setup 0, thenpassive setup 0. - Click:
layout cleanup 0,layout setup 1,passive cleanup 0,passive setup 1. - Unmount:
layout cleanup 1, thenpassive cleanup 1. - Layout effects run synchronously during the commit, before the browser paints. Passive effects run afterwards. For an update, each kind runs its cleanups before its setups, and layout work comes first.
StrictMode and an interval that never stops
Puzzle 5. StrictMode is on. A component starts setInterval in an effect that runs on mount, with 20 ms between ticks, and increments a counter. One version returns a cleanup that calls clearInterval, the other returns nothing. After 210 ms, how do the two counters compare?
function Ticker({ clean }: { clean: boolean }) { const [ticks, setTicks] = useState(0) useEffect(() => { const id = setInterval(() => setTicks((t) => t + 1), 20) return clean ? () => clearInterval(id) : undefined }, [clean]) return <output>{ticks}</output> }
Puzzle 5: why are the counts different?
- Real output:
P5 clean = false | ticks after 210 ms: 14andP5 clean = true | ticks after 210 ms: 7. The version without a cleanup shows twice the ticks. The counts depend on timer speed on this machine and vary between machines. - In development,
StrictModeruns the effect, its cleanup and the effect again on mount. Without a cleanup, the first interval keeps running next to the second one, so the counter advances twice as fast. The cleanup stops the first interval before the second starts. - The ratio of two to one is what this puzzle shows, not the exact numbers.
- The leak is real in production too. Without
StrictModeit shows up when the component unmounts: the interval keeps running and keeps calling the setter of a component that no longer exists. StrictMode makes the missing cleanup obvious on the first render.
Check your understanding
In what order do effects of a parent and its child run on mount?
- Child first, then parent. Rendering is top-down, effects are bottom-up.
An effect has [a] as dependencies but reads b. What can go wrong?
- It runs when
achanges and sees whateverbis then, but does not run when onlybchanges. The linter flags this.
Why does StrictMode run an effect, its cleanup and the effect again on mount?
- To expose effects whose cleanup does not undo their setup. It runs in development only.
Part 3 · Identity and keys
State follows position and type
React decides whether a component is the same one as last time by comparing its type and position in the tree, and its key if it has one. The same identity keeps its state. A different identity gets a fresh component with fresh state. These puzzles use a small Counter that shows a label and a click count.
function Counter({ label }: { label: string }) { const [n, setN] = useState(0) return ( <button onClick={() => setN(n + 1)}> {label} {n} </button> ) }
Puzzle 1. A parent renders <Counter label="mine" /> or <Counter label="yours" /> in the same place, depending on a swap button. The user clicks the counter twice, then presses swap. What does the counter show?
function SameType() { const [mine, setMine] = useState(true) return ( <> <button onClick={() => setMine(!mine)}>swap</button> {mine ? <Counter label="mine" /> : <Counter label="yours" />} </> ) }
Puzzle 1: what is shown?
yours 2. The typeCounteris the same at the same position, so React kept the instance and its state. Only the label prop changed.
Puzzle 2. A parent shows the same Counter inside a div, or inside a section after a wrap button is pressed. The user clicks twice, then presses wrap. What does it show?
function Wrapped() { const [boxed, setBoxed] = useState(false) return ( <> <button onClick={() => setBoxed(!boxed)}>wrap</button> {boxed ? ( <section> <Counter label="c" /> </section> ) : ( <div> <Counter label="c" /> </div> )} </> ) }
Puzzle 2: what is shown?
c 0. The wrapper changed fromdivtosection, which is a different type at that position, so React discarded the whole subtree and created a new one with fresh state.
Keys and components defined in components
Puzzle 3. A parent renders <Counter key={id} label={'user ' + id} />. The user clicks twice, then presses next, which adds one to id. What does it show?
function Keyed() { const [id, setId] = useState(1) return ( <> <button onClick={() => setId(id + 1)}>next</button> <Counter key={id} label={'user ' + id} /> </> ) }
Puzzle 3: what is shown?
user 2 0. A new key means a new identity, so React created a freshCounter. This is the cleanest way to reset a component's state.
Puzzle 4. Outer has a state counter and defines a function component Inner inside its own body. Inner logs from an effect when it mounts and when it unmounts. The user clicks the re-render button once. What is logged around the click?
function Outer() { const [n, setN] = useState(0) function Inner() { useEffect(() => { console.log('P4 Inner mounted') return () => console.log('P4 Inner unmounted') }, []) return <p>inner</p> } return ( <> <button onClick={() => setN(n + 1)}>rerender {n}</button> <Inner /> </> ) }
Puzzle 4: what is logged?
- Before the click:
P4 Inner mounted. - After the click:
P4 Inner unmounted, thenP4 Inner mounted. - Each render of
Outercreates a newInnerfunction, which React sees as a new type, so it unmounts the old one and mounts a new one, losing its state. The lastunmountedline in the full log is the test ending. - Define components at the top level of a module, never inside another component.
Index keys
Puzzle 5. A list of three inputs is rendered with key={i}, the array index. Each input starts with its own name as a default value: Anil, Bela and Chitra. The user types an exclamation mark into the first input, then presses a button that removes the first name from the data. What do the two remaining inputs contain?
function Rows() { const [rows, setRows] = useState(['Anil', 'Bela', 'Chitra']) return ( <> <button onClick={() => setRows(rows.slice(1))}>drop first</button> {rows.map((name, i) => ( <input key={i} aria-label={name} defaultValue={name} /> ))} </> ) }
Puzzle 5: what do the inputs contain?
Anil!andBela.- With index keys, the input at index 0 stays, and so does its typed text, even though the first row is now Bela. The input at index 1 stays too and still shows
Bela, although its row is now Chitra. React matched the inputs by position, so the text no longer belongs to its row. - Keys should come from the data, such as an id, so the typed text moves with its row. Here the fix is one line,
key={name}, or better a stable id. A key must be unique among its siblings and stable across renders, which an index is not once the list can change order, grow at the top or lose items.
Check your understanding
What identity rule keeps a component's state?
- The same type at the same position in the tree, with the same key if it has one.
Why should a component never be defined inside another component?
- Each render of the outer component creates a new function, which React treats as a new type, so the inner component remounts every time and loses its state.
How do you reset a component's state from outside?
- Give it a different
key. A new key creates a fresh instance.
Part 4 · Closures, transitions and Suspense
Stale values
A closure keeps the values from the render that created it. That is useful and sometimes surprising. The first two puzzles are the two most common stale-value bugs.
Puzzle 1. A click handler calls setN(n + 1) and also starts a 20 ms timer that logs n. The user clicks twice, with the first click completing before the second. What do the two timers log?
function Late() { const [n, setN] = useState(0) return ( <button onClick={() => { setN(n + 1) setTimeout(() => console.log('P1 timer sees', n), 20) }} > add {n} </button> ) }
Puzzle 1: what do the timers log?
P1 timer sees 0and thenP1 timer sees 1.- Each timer's function closed over the
nof the render in which its click happened: 0 for the first and 1 for the second. Neither sees the latest value.
Puzzle 2. An effect with an empty dependency list starts a 20 ms interval. In one version it calls setN(n + 1), and in the other setN((x) => x + 1). After 110 ms, what does each component show?
function Interval({ updater }: { updater: boolean }) { const [n, setN] = useState(0) useEffect(() => { const id = setInterval(() => { if (updater) setN((x) => x + 1) else setN(n + 1) }, 20) return () => clearInterval(id) }, []) return <output>{n}</output> }
Puzzle 2: what do the counters show?
- Real output:
P2 updater = false | after 110 ms: 1andP2 updater = true | after 110 ms: 4. The first shows 1, and it stays at 1 however long you wait. The interval's function closed overnequal to 0, so every tick asks for 1. - The second keeps climbing: 4 in the run above, and 3 or 4 when the run was repeated. The updater reads the latest state, so it does not depend on the closure. The exact count varies.
- The other fix is to list
nas a dependency, which restarts the interval on every change.
Transitions after await, and deferred values
Puzzle 3. An Action started with startTransition from useTransition waits 20 ms, then sets done to true. In one version, the update is wrapped in a second startTransition. In the other it is not. The component logs isPending and done on every render. How do the logs differ?
function AfterAwait({ wrapped }: { wrapped: boolean }) { const [isPending, start] = useTransition() const [done, setDone] = useState(false) console.log( 'P3 wrapped =', wrapped, '| pending', isPending, '| done', done ) return ( <button onClick={() => start(async () => { await wait(20) if (wrapped) startTransition(() => setDone(true)) else setDone(true) }) } > go </button> ) }
Puzzle 3: how do the logs differ?
- Real output, unwrapped:
pending false, done false,pending true, done false,pending true, done true,pending false, done true. That is four renders. - Real output, wrapped:
pending false, done false,pending true, done false,pending false, done true. That is three renders, ending with both changes in one step. - An update after an
awaitinside an Action is not marked as a transition, so it renders on its own, while the Action is still pending, and the pending flag clears in a later render. Wrapping the update instartTransitionkeeps it with the Action.
Puzzle 4. A search box keeps its text in state and passes it to useDeferredValue. The component logs the text and the deferred text on every render. The user types a, then b. What are the five lines?
function Search() { const [q, setQ] = useState('') const deferred = useDeferredValue(q) console.log( 'P4 render: q =', JSON.stringify(q), '| deferred =', JSON.stringify(deferred) ) return ( <input aria-label="q" value={q} onChange={(e) => setQ(e.target.value)} /> ) }
Puzzle 4: what are the lines?
- Real output:
q = "" | deferred = "",q = "a" | deferred = "",q = "a" | deferred = "a",q = "ab" | deferred = "a",q = "ab" | deferred = "ab".
Suspense boundaries
Puzzle 5. Two components read promises with use: a resolves after 20 ms and b after 80 ms. In one version they share one Suspense boundary. In the other each has its own. What does the page text read at 50 ms and at 150 ms in each version? This puzzle reads the page at fixed times, so it depends on timers; the gaps between them are wide, and repeated runs gave the same text.
function Item({ name, ms }: { name: string; ms: number }) { return <p>{use(load(name, ms))}</p> }
Puzzle 5: what does the page read?
- Real output:
split = false | at 50 ms: [wait] | at 150 ms: a readyb readyandsplit = true | at 50 ms: a ready[wait b] | at 150 ms: a readyb ready. - One boundary:
[wait]at 50 ms, thena readyb readyat 150 ms. The boundary shows its fallback until every child it covers is ready. - Two boundaries:
a ready[wait b]at 50 ms, then both ready at 150 ms. Each boundary reveals as soon as its own content is ready. - Place boundaries where independent parts of the page can appear independently.
These four lessons share one habit. Before you guess, write down which render each value belongs to, which component created each element, and which update is a transition. Then check against a run. When the real output surprises you, find which of those three you had wrong.
Check your understanding
Why does the interval in Puzzle 2 stay at 1?
- Its function closed over
nequal to 0 in the first render, because the effect never re-runs. The updater form reads the latest state instead.
What does wrapping the update after an await in startTransition change?
- The update stays with the Action: one render shows both
doneand the cleared pending flag, instead of an extra render in between.
Why do two Suspense boundaries reveal content at different times?
- Each boundary shows its fallback until the content it covers is ready, independent of the others.
All chapters · Previous: Machine Coding Practice: Timed UI Builds