Search code examples
javascriptreactjssetintervalclearintervalreact-component-unmount

When clearInterval will be called - When the timer changes or When the render is unmounted with which the setInterval is associated


I'm a beginner in React and stuck with some problem. When the setInterval associated with a particular renders gets cleared?



import React, { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom";

function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    let id = setInterval(() => {
      setCount(count + 1);
    }, 1000);
    return () => clearInterval(id);
  },[]);

  return <h1>{count}</h1>;
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Counter />, rootElement);

Solution

  • It will get cleared on component unmount event :

    useEffect(() => {
        let id = setInterval(() => {
          setCount(count + 1);
        }, 1000);
        return () => clearInterval(id); // <-- get called on component unmount
      },[]); // <--- get called once component mounted/rendered first time
    

    For more details : DO READ

    When exactly does React clean up an effect?

    React performs the cleanup when the component unmounts. However, as we learned earlier, effects run for every render and not just once. This is why React also cleans up effects from the previous render before running the effects next time.