Pass setScore a function instead of a value, and three updates really add three.
React · beginner · 7 min · 15 steps · free
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>
);
}<Score> for the first time: it calls the Score function.useState runs for the first time, so React stores the starting value for score and returns it: 0.Score returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.onClick handler.s = 0, so it returns 1.setScore((s) => s + 1) queues a function, not a value: "take the latest score and add 1".<Score> again (render 2): it calls Score once more, from the top.s = 1, the result of the first, and returns 2.s = 2 and returns 3.useState returns 3.Score returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.Answer: 8. 1 → 2 → 4 → 8.
Answer: The latest state
← State Is a Snapshot · Updating Objects in State →