useEffect cleanup / memory leak

444 Views Asked by At

I have wrote a ReactJS web application. This is a Single Page Application (SPA). I have a menu with several Pages. Each page is a .js file. Due to SPA, my browser is not refreshing full page when i change page in my menu.

Here is what i put on every pages:

const myPageLoad = useCallback(async () => {
   // loading data
}, []);

useEffect(() => {
  myPageLoad();
}, [myPageLoad]); 

"Loading data" can take 3-4 seconds to load data. It works fine.

If i decide to change page from my menu before "loading data" has finished, i get this warning in javascript console:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. in Data (created by Context.Consumer)

I think i have to cancel my loading traitement if i detect a page change. But how can i do that ?

Thanks a lot

1

There are 1 best solutions below

0
On

You can use an abort, I fix this kind of error this way:

useEffect(() => {
  // get abortion variables
  let abortController = new AbortController();
  let aborted = abortController.signal.aborted; // true || false
  async function fetchResults() {
    let response = await fetch(`[WEBSITE LINK]`);
    let data = await response.json();
    aborted = abortController.signal.aborted; // before 'if' statement check again if aborted
    if (aborted === false) {
      // Make sure all your 'set states' inside this kind of 'if' statement
      setState(data);
    }
  }
  fetchResults();
  // make sure to return this abort()
  return () => {
    abortController.abort();
  };
}, [])

Other Methods: https://medium.com/wesionary-team/how-to-fix-memory-leak-issue-in-react-js-using-hook-a5ecbf9becf8