Murugesh Aravind
Murugesh Aravind

Reputation: 41

How to avoid the memory leak warning in my react application, even though i am cleaning up my useEffect?

Warning: Can't perform React state update on the unmounted component

App.js

App.js

App.js

After using the useIsMount approach, i am unable to pass the state value as props

Upvotes: 0

Views: 415

Answers (1)

JMadelaine
JMadelaine

Reputation: 2964

This happens when you try to set state on a component that has already unmounted. This is commonly seen in async operations where you make an async request, and then you try to set state once it resolves.

The process goes like this:

  1. Component mounts
  2. useEffect runs and fires the async request
  3. The async function creates a closure around the set state function
  4. The component unmounts (due to a change in UI for whatever reason)
  5. The request resolves
  6. The closured set state function is called - but the component that contains the state has already unmounted! Error happens here.

To fix this, you need to check to see if the component is still mounted before you call the state update function.

You can check to see if a component is mounted by using something like a useIsMounted hook. There are many examples of this hook online.

HMR commented with a link to a good useIsMounted hook, which I'l post here:

import { useRef, useEffect } from 'react';

const useIsMounted = () => {
  const isMounted = useRef(false);
  useEffect(() => {
    isMounted.current = true;
    return () => isMounted.current = false;
  }, []);
  return isMounted;
};

export default useIsMounted;

To use the hook, you call it in your component:

const isMounted = useIsMounted()

And inside your async function, check to see if the component is mounted before setting state:

if(isMounted.current) {
  // it's okay to set state here
}

Make sure you add the isMounted variable as a dependency of your useEffect so you have the most up to date value!

Upvotes: 2

Related Questions