search

Home  >  Q&A  >  body text

setInterval Unlimited re-rendering of react-complete components. Why does this happen and how to fix it?

This is my react code. It makes the component re-render infinitely:

const [seconds, setSeconds] = useState(60)
useEffect(() => {
    const interval = setInterval(() => {
        setSeconds(seconds => seconds - 1);
    }, 1000);
    return () => clearInterval(interval);
}, []);

console.log("object");

P粉978742405P粉978742405274 days ago531

reply all(1)I'll reply

  • P粉476046165

    P粉4760461652024-04-04 14:48:25

    This happens because you only clear the interval when the component unloads, which only happens when the user navigates away from the page.

    Maybe this is what you need? When the interval reaches 0, I clear it. But for this I have to use reference, I can't use state from setInterval because it only has initial value:

    export default function App() {
      const [seconds, setSeconds] = useState(5);
      const secondsRef = useRef(seconds);
    
      useEffect(() => {
        const interval = setInterval(() => {
          if (secondsRef.current < 0) {
            clearInterval(interval);
          }
    
          secondsRef.current = secondsRef.current - 1;
          setSeconds((seconds) => seconds - 1);
        }, 1000);
        return () => clearInterval(interval);
      }, []);
    
      console.log("running", new Date());
    
      return 

    {seconds < 0 ? "Time is up!" : seconds}

    ; }

    reply
    0
  • Cancelreply