useState Under the Hood: How React Stores State in a Linked List

Hands-on practice for this lecture. Work through the exercises and quizzes to reinforce what you've learned.

1

Exercise 1 of 3

Predict the Count

Three setCount calls fire in one handler. What does the counter show after one click? Test your understanding of React state batching.

Code

const [count, setCount] = useState(0);

function handleClick() {
  setCount(count + 1);
  setCount(count + 1);
  setCount(count + 1);
}

After one click, what does count show?

Pick an answer

πŸ’‘ Stale closure: each call reads the count from the current render snapshot. To chain updates safely, always pass a callback: setCount(prev => prev + 1).

2

Exercise 2 of 3

Direct vs Functional Update

See live how direct updates collapse when called 3Γ— in one handler, while functional updates chain correctly. Toggle between both patterns.

Both buttons call a setter 3 times in one handler. Watch the counts diverge.

Direct update

setCount(count + 1) // Γ—3
0

Functional update

setCount(prev => prev + 1) // Γ—3
0

πŸ’‘ After one click: direct update counts 1 (all three calls saw the same snapshot), functional update counts 3 (each callback receives the latest queued value).

3

Exercise 3 of 3

Fix the Triple Increment

Live editor: the counter only adds 1 when it should add 3. Fix the stale closure by switching to the functional updater form.

Task

The button should add 3 to the count on each click. Right now it only adds 1. Fix handleTripleIncrement so all three increments take effect.

Loading editor…

πŸ’‘ Hint: all three setCount calls read the same stale count from this render. How can you make each call see the result of the previous one?

Practice: useState Under the Hood: How React Stores State in a Linked List β€” Interactive Exercises | Durgesh Rai