'Why stops useEffect Hook?

In my application I want to display a timer which can be started and stopped by the user. For this I created a timer state: const [timer, setTimer] = useState({"minutes" : 0, "seconds" : 0})and use a useEffect hook to increment the values periodically.

If I'm using:

useEffect(() => {
  const displayTimer = setTimeout(() => {
    if(timer.seconds < 59) {
      setTimer({"minutes": timer.minutes, "seconds" : timer.seconds + 1})
    }
    else {
      setTimer({"minutes": timer.minutes + 1, "seconds" : 0})
    }
  }, 1000);
  return () => clearTimeout(displayTimer);
});

everything works fine. The timer runs until infinity. But after adding the if statement, to stop the timer, nothing happens anymore. I can't start the timer.

Heres the code:

useEffect(() => {
  const displayTimer = setTimeout(() => {
    if(active) {
      if(timer.seconds < 59) {
        setTimer({"minutes": timer.minutes, "seconds" : timer.seconds + 1})
      }
      else {
        setTimer({"minutes": timer.minutes + 1, "seconds" : 0})
      }
    }
  }, 1000);
  return () => clearTimeout(displayTimer);
});

The active var is a useState hook which is toggled by a button.
With console.log I found out, the useEffect isn't called anymore after adding the if. But why? Can anyone help me to get my timer working?



Solution 1:[1]

The effect function closes over the active variable's initial state, so it will always be true.

All dependencies need to be included in the dependencies array of the effect, like useEffect(() => {}, [active])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 windowsill