State Is a Snapshot

Call setScore(score + 1) three times in one click. Why does the score only go up by one?

React · beginner · 7 min · 12 steps · free

What you'll learn

StateSnapshot.jsx

import { useState } from 'react';

export default function Score() {
  const [score, setScore] = useState(0);

  function addThree() {
    setScore(score + 1);
    setScore(score + 1);
    setScore(score + 1);
  }

  return (
    <div>
      <h2>Score: {score}</h2>
      <button onClick={addThree}>+3</button>
    </div>
  );
}

Step by step

  1. React renders <Score> for the first time: it calls the Score function.
  2. useState runs for the first time, so React stores the starting value for score and returns it: 0.
  3. Score returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  4. React turns the JSX into real page elements and shows them: look at the Screen panel.
  5. You click the “+3” button. React calls its onClick handler.
  6. First setScore(score + 1): score is 0 in this render, so this queues "set score to 1".
  7. Second call: score is still 0, so it queues "set to 1" again.
  8. Third call: the same. Queued updates now holds three updates, all → 1.
  9. React renders <Score> again (render 2): it calls Score once more, from the top.
  10. React applies the three updates in order: 1, then 1, then 1. score is 1, not 3.
  11. Score returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  12. Score: 1. The button said +3, but every update was "set to 1".

Common mistakes

Best practices

Key takeaways

Check yourself

setX(x + 1); setX(x + 1); with x = 5 gives?

Answer: 6. Both read x = 5.

When does the new value appear?

Answer: In the next render

·

More in State and Events