Time Remaining4:00
mediumRace ConditionsReact

The stale React closure

The following component is intended to display a timer that increments every second. However, users report that the number gets stuck at 1 and never increments further. Why is this happening?

TimerComponent.jsx
import { useState, useEffect } from 'react';

export default function TimerComponent() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const intervalId = setInterval(() => {
      setCount(count + 1);
    }, 1000);

    return () => clearInterval(intervalId);
  }, []);

  return <div>Timer: {count}</div>;
}

What is causing the counter to get stuck at 1?

The effect hook dependency array is empty, closing over the initial value of count (0) inside the interval callback.
setInterval is not supported inside useEffect unless configured as a Web Worker.
The clean-up function clearInterval is called immediately, stopping the interval after one tick.
setCount should be called asynchronously with a await keyword inside the interval.