React · Middle · Question 11 of 75

Why does the counter stop at 1?

const [count, setCount] = useState(0);

useEffect(() => {
  const id = setInterval(() => setCount(count + 1), 1000);
  return () => clearInterval(id);
}, []);

Explanation

The effect with [] is created once and sees count from the first render. Each tick sets 0 + 1. Fixes: a functional update setCount(c => c + 1) (best), adding count to dependencies (the interval is recreated), or keeping the value in a ref.

Further reading

Problem with a question

React · Middle · question 11

Test yourself

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

Take this quiz