Why Does My React Counter Stop at 1 When I Use setInterval?

Asked 5 days ago 57 views

0

I’m building a small elapsed-time counter in React. The interval keeps running, but the number on screen changes from 0 to 1 and then stays there.

import { useEffect, useState } from "react";

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

  useEffect(() => {
    const timerId = setInterval(() => {
      // Attempt to increase the displayed count once per second.
      setCount(count + 1);
    }, 1000);

    // Stop the interval when this effect is cleaned up.
    return () => clearInterval(timerId);
  }, []);

  return <p>{count}</p>;
}

My linter flags count as a missing dependency. Adding it makes the counter advance, but it also seems to recreate the interval after every update.

How do stale closures in React explain this behavior? Should I use a functional state update here, or include count in the dependency array? I’m trying to understand the difference rather than just silence the warning.

0 Answers


Write Your Answer