Update Functions

Pass setScore a function instead of a value, and three updates really add three.

React · beginner · 7 min · 15 steps · free

What you'll learn

UpdaterFunctions.jsx

import { useState } from 'react';

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

  function addThree() {
    setScore((s) => s + 1);
    setScore((s) => s + 1);
    setScore((s) => s + 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. The first update function runs at once: the queue was empty, so React works out the new value early. s = 0, so it returns 1.
  7. setScore((s) => s + 1) queues a function, not a value: "take the latest score and add 1".
  8. A second function goes into the queue.
  9. And a third. Queued updates holds the functions themselves.
  10. React renders <Score> again (render 2): it calls Score once more, from the top.
  11. Now React renders and runs the rest of the queue in order. The second function gets s = 1, the result of the first, and returns 2.
  12. The third gets s = 2 and returns 3.
  13. useState returns 3.
  14. Score returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  15. Score: 3. Update functions build on each other, so +3 really adds 3.

Common mistakes

Best practices

Key takeaways

Check yourself

setN(n => n * 2) three times, from 1?

Answer: 8. 1 → 2 → 4 → 8.

What does the function receive?

Answer: The latest state

·

More in State and Events