Can't Perform a React State Update on an Unmounted Component
React Warning “Can't perform a react state update on an unmounted component” is caused when we try to update the state after the component was unmounted.
To solve the issue we can set a flag to determine whether the component was unmounted or not.
Below is the sample code.
import {useState, useEffect} from 'react';
const App = () => {
const [state, setState] = useState('');
useEffect(() => {
// set isMounted to true
let isMounted = true;
someAsyncOperation().then(data => {
if (isMounted) setState(data); // add conditional check
});
return () => {
// when component unmounts, set isMounted to false
isMounted = false;
};
}, []);
return (
<div>
<h2>State: {JSON.stringify(state)}</h2>
</div>
);
};
export default App;
Here we have initialized isMounted
flag in useEffect
and set it to true
. And, this flag was checked before we updating the state after async operation as given below.
let isMounted = true;
someAsyncOperation().then(data => {
if (isMounted) setState(data); // add conditional check
});
The function returned from the useEffect hook will be executed when the component unmounts. So we set isMounted
variable into false
in useEffect
return function as given below.
return () => {
// when component unmounts, set isMounted to false
isMounted = false;
};
Learn using the Effect Hook and cleanup in react.