Skip to content
Advertisement

How to ClearInterval outside of UseEffect?

Saw a few questions similar to this, but was not able to find an answer.

When the page loads, I want to start running these 2 functions (http requests). However, when there is an error, I want to be able to ClearInterval. However, given that those 2 setIntervals are invoked and declared within useEffect, I’m unable to clear it outside.

const [error, setError] = useState("");

// fetchSnapshot function here
// fetchData function here

useEffect(() => {
    setInterval(fetchSnapshot, 5000);
    setInterval(fetchData, 5000);
  }, []);

This seems like a scope issue but I’m not sure how to solve this.

I’ve tried several solutions like

  • Declaring a variable globally and then update it within the useEffect. This did not work for me, likely because the setInterval was declared and invoked inside.
  • Setting the dependency array as the local error state and then adding an IF statement within the useEffect to trigger the clearInterval, but didn’t really work out…

I need the clearInterval to only trigger if my local error state is updated and no longer falsy. Any ideas would be appreciated.

Advertisement

Answer

Use a ref to store the interval ids. Clear them when your state variable changes.

const [error, setError] = useState("");
const snapshotIntervalRef = useRef();
const dataIntervalRef = useRef();

// fetchSnapshot function here
// fetchData function here

useEffect(() => {
   snapshotIntervalRef.current = setInterval(fetchSnapshot, 5000);
      dataIntervalRef.current = setInterval(fetchData, 5000);

    return () => {
      clearInterval(snapshotIntervalRef.current);
      clearInterval(dataIntervalRef.current);
   };

}, []);


useEffect(() => {
if(error) {
      clearInterval(snapshotIntervalRef.current);
      clearInterval(dataIntervalRef.current);
}

},[error]);

I have added a cleanup function in first useEffect. That is to avoid memory leaks, but the relevant solution is in the second useEffect

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement