See error logs in your console with the message “Cannot perform state update on an unmounted component” from your React application? There is a simple cause and easy fix.
React components which run asynchronous operations and perform state updates can cause memory leaks if state updates are made after the component is unmounted. Here is a common scenario where this could pop up:
Since the component was unmounted, a state setter function is being called in a component that is no longer mounted. Essentially, the setter function is updating state no longer exists. Memory Leak.
Here is a contrived example of unsafe code:
const [value, setValue] = useState({});
useEffect(() => {
const runAsyncOperation = () => {
setTimeout(() => {
// MEMORY LEAK HERE, COMPONENT UNMOUNTED
setValue({ key: 'value' });
}, 1000);
}
runAsyncOperation();
// USER NAVIGATES AWAY FROM PAGE HERE,
// IN LESS THAN 1000 MS
}, []);
#web-development #react #javascript #react-hook #custom-react-hook