Follow a counter button through its first render, a click, and the re-render that puts the new number on screen.
React · beginner · 8 min · 8 steps · free
useState is only used on the first renderimport { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<button onClick={handleClick}>
Clicked {count} times
</button>
);
}Counter function.useState(0) asks React to remember a value for this component. On the first render React stores 0 and hands it back, so count is 0.count filled in. React turns that into a real button on the page: look at the Screen panel.handleClick, the function this render attached with onClick.setCount(count + 1) works out 0 + 1 and asks React to use 1 on the next render. It does not change count here: inside this render, count is still 0.Counter a second time from the top.useState(0) ignores the 0. That starting value is only used on the first render, so React hands back the stored value, 1.count. React compares it with what is on the page and updates only the text that changed, so the screen now says 1.count right after setCount and expecting the new valuecount = count + 1, which React never noticessetCount(c => c + 1)useState keeps a value between renders; its argument is only the very first value.Answer: Calling its state setter, like setCount. Only a state change (or a parent re-render) makes React call the component again.
setCount(count + 1), in the same function, what is count?Answer: The old value. The new value only appears in the next render.
← Rendering Lists with Keys · Handling Events →