React 5 second timer crashes

Once the timer reaches 5 seconds, it crashes with this error: " Too many re-renders. React limits the number of renders to prevent an infinite loop.". Can someone please point me to the mistake that’s causing this? https://codepen.io/Montinyek/pen/zYLzBZP?editors=1111

function App() {
  const [secs, setSecs] = React.useState(0);
  const [ms, setMs] = React.useState(0);
  const [done, setDone] = React.useState(false)
  
  React.useEffect(() => {
    let interval = setInterval(() => {
      if (!done) {
        setMs(prev => prev += 1)
      } 
}, 10);
    return () => clearInterval(interval);
  }, [done])
  
  function time() {
    if (ms === 100) {
    setMs(0)
    setSecs(prev => prev += 1)
    }
    if (secs === 5) {
    setDone(true)
    }
    let formattedSecs = secs < 10 ? "0" + secs : secs;
    let formattedMils = ms < 10 ? "0" + ms : ms;
    return `${formattedSecs} : ${formattedMils}`;
  }

  return <div>{time()}</div>;
}

ReactDOM.render(<App />, document.getElementById("root"));

Not sure but I think that when you modify done state in your time () function, the useEffect enters into a loop. If you remove setDone(true) the loop it’s not made.
If you want to stop the time when it reaches 5 secs, you can tell useEffect to watchs for secs and in the if statement see if secs != 5.

I tried something similar with an else if and it didn’t work

Can someone please take a look?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.