I’m trying to set up a setInterval in a useEffect for an async function that fetches from a URI. I’m using React Router DOM to set up a few pages for the app. The problem I’m facing is that a memory leak is occurring when using setInterval. I check the devtools performance and memory tabs, and also the browser task manager (ex: in both Edge and Chrome), and the memory being used increases rapidly until the browser errors out on the page with “Out of memory”.
Another problem I noticed is that when changing to another page of the app, set up with routes from React Router, the function in the interval is somehow still running when on another page, according to the Performance tab.
How can I set this up so there’s no memory leak, and how to cancel the interval when going to another route/page? I tried several different things with clearInterval, and nothing seems to stop the function from still running on an interval when on the other page.
Example code:
useEffect(() => {
setInterval(fetchFunction, 30000);
}, []);
I tried using useRef, and a return function variation to clear the interval, to no success. For example:
// timedFunction is a state variable that holds the setInterval
useEffect(() => {
setTimedFunction(setInterval(fetchFunction, 30000));
return () => {
clearInterval(timedFunction);
};
}, []);
1