React: setInterval inside useEffect keeps reading a stale state value
@devsingh05▲ 10 net votes
The interval callback closes over the state from the render where the effect ran, so with an empty dependency array it always sees the initial value. Use the functional updater (setCount(c => c + 1)), keep the latest value in a ref, or include the value in the dependencies and clear the interval in the cleanup. Always return () => clearInterval(id) from the effect.