Reputation: 41
Warning: Can't perform React state update on the unmounted component
After using the useIsMount approach, i am unable to pass the state value as props
Upvotes: 0
Views: 415
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:
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