0

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);
};
}, []);
2
  • const id = setInterval(fetchFunction, 30000); return () => clearInterval(id); Commented Jun 26, 2024 at 23:49
  • I tried that, too. It still causes the page to hog up more and more memory until the page crash. And also, the interval based function is somehow running when going to another page/route the same way still. Commented Jun 27, 2024 at 0:24

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.