State Management · Junior · Question 2 of 75
Why doesn't the counter on screen change?
function Counter() {
let count = 0;
return <button onClick={() => count++}>{count}</button>;
}- ✓Correct answer: A local variable isn't preserved between renders and changing it doesn't trigger a render
- 2
onClickhandlers can't modify variables declared in the component - 3The button needs
type="button"for the click to update the text
Explanation
count is recreated as 0 on every render, and incrementing it doesn't ask React to re-render. You need const [count, setCount] = useState(0) and setCount(count + 1).