I’m building a small timer in React. The counter changes from 0 to 1 and then stays there, but the message inside the interval keeps appearing in the console.
import { useEffect, useState } from "react";
export default function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
// Check whether the callback continues after the first update.
console.log("Interval fired");
setCount(count + 1);
}, 1000);
// Remove the interval when the effect is cleaned up.
return () => clearInterval(timer);
}, []);
return <p>{count}</p>;
}
I left the dependency array empty because I wanted to create the interval only once. My assumption was that its callback would still read the latest state whenever it ran.
Is this an example of stale closures in React? I’ve seen suggestions to add count to the dependency array or use a functional state update, but those seem to change the behavior in different ways. Which approach fits a continuously running timer, and why?