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.

The Cause

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:

  1. User performs an action triggering an event handler to fetch data from an API.
  2. The user clicks on a link, navigating them to a different page, before (1) completes.
  3. The event handler from (1) completes the fetch, and calls a state setter function, passing it the data that was retrieved from the API.

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

How to Fix Memory Leaks with a Simple React Custom Hook
16.65 GEEK