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
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>
);
}<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.setScore(score + 1): score is 0 in this render, so this queues "set score to 1".score is still 0, so it queues "set to 1" again.<Score> again (render 2): it calls Score once more, from the top.score is 1, not 3.Score returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.Answer: 6. Both read x = 5.
Answer: In the next render
← Handling Events · Update Functions →