Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

incremental value using setInterval in react broken

function App() {
  const [tick, setTick] = useState(0);
  useEffect(() => {
    setInterval(() => {
      setTick(tick + 1);
    }, 1000);
  }, [tick]);

  return (
    <div className="App">
      <h1>{tick}</h1>
    </div>
  );
}

it turned out to be incrementing more than 1 per second, it worked at the beginning and it started to messed up later. See demo https://codesandbox.io/s/eloquent-kepler-vvzr7

like image 718
Jennifer Avatar asked Dec 21 '25 18:12

Jennifer


1 Answers

Cause every time you update the tick, the effect triggers and starts another timer... The effect shall not depend on tick:

 useEffect(() => {
    let id = setInterval(() => {
      setTick(tick => tick + 1); // No dependency anymore
    }, 1000);

    // This has nothing todo with your problem, but I encourage you to correctly clean up effects:
    return () => clearInterval(id);
 }, []); // <<
like image 94
Jonas Wilms Avatar answered Dec 23 '25 08:12

Jonas Wilms