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>;
}

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).

Further reading

Problem with a question

State Management · Junior · question 2

Test yourself

Take the State Management · Junior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz