useEffect not updating countdown timer

Hi guys,

I have just learned about useState, useEffect hooks and tried building a timer using these but I guess I am doing something wrong because the timer is acting weird. Can someone look at the code below and advise what did I do wrong here:


const FocusModeView2 = (props) => {
  const [minsLeft, setMinsLeft] = useState(props.focusPeriod);
  const [secsLeft, setSecsLeft] = useState(0);

  useEffect(() => {
    let startTime = Date.now();
    let timeLength = minsLeft * 60 * 1000;
    let endTime = startTime + timeLength;
    let timer = setInterval(() => {
      let currentTime = Date.now();
      let newMinsLeft = Math.floor((endTime - currentTime) / (1000 * 60));
      let newSecsLeft = Math.round(((endTime - currentTime) / 1000) % 60);
      setMinsLeft(newMinsLeft);
      setSecsLeft(newSecsLeft);
      if (minsLeft <= 0 && secsLeft <= 0) {
        clearInterval(timer);
      }
    }, 1000);
  });

  return (
    <div>
      <div>
        {minsLeft} : {secsLeft}
      </div>
    </div>
  );
};

The problem is when you use useEffect() you should use dependency array or the function will rerender forever so useEffect({}) should be useEffect({}, []).
To know more about dependency array you can read this article:

1 Like

Thanks. I guess I never learned about this part. :slight_smile:

1 Like

You are welcome. It’s important when you learning new technologies to read the official documentation.

1 Like