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);
}, []);- 1
setIntervalcan't be used inside effects - ✓Correct answer: The callback closed over
count = 0from the first render - 3
clearIntervalfires right after the first tick
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.