ValueError: Can’t perform a React state update on an unmounted component in React-hooks – How To Fix?

Can’t perform a React state update on an unmounted component in React-hooks

Are you finding the way to fix the error “ValueError: Can’t perform a React state update on an unmounted component” in React-hooks? Let’s follow this article. We will help you to fix it.

The cause of this error

If you try to update a component’s state after it’s unmounted, React will give you a warning that it will become error. The problems often encountered when we use unhashable objects as keys in our dictionaries. 

This function will attempt to update the state of an unmounted component when the fetch is started.

Example

default function React() {
    const [notFoundAmount, setNotFoundAmount] = useState(false);

    useEffect(() => {
        let timer = setInterval(updateNotFoundAmount, 2000);
        return () => clearInterval(timer);
    }, []);

    async function updateNotFoundAmount() {
		// Here I'm fetching data
      	let data; 
		// Here is the problem. If the component were unmounted, it would get the error.
        setNotFoundAmount(data);
    }

    async function moreFunction() {
      	// It can trigger update, too
       	updateNotFoundAmount();
    }

  	// Update can be triggered manually
    return <button onClick={updateNotFoundAmount}>Push me</button>;
}

The error will show if you tries to run the code above.

index.js:1452 Warning: Can't perform a React state update on an unmounted component.
This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

How to solve the error “Can’t perform a React state update on an unmounted component” in React-hooks?

Method 1: Keep an eye on the component

Here is an example implementing it with hooks. An easy method to get rid of the warning is to keep an eye on the component is mounted using an isStopped boolean in our useEffect hook. This is a typical pattern with the class-based approach.

function Example() {
    const[text, setText] = React.useState("Please wait…");

    React.useEffect(() => {
        let isStopped = false;

        simulateSlowNetworkRequest().then(() => {
            if (!isStopped) {
              	setText("OK!");
            }
        });

        return () => {
          	isStopped = true;
        };
    }, []);

    return <h2>{text}</h2>;
}

Method 2: Use ‘useRef’

Here is an alternative with useRef. But in some case, the first solution is more appropriate. Because this solution won’t work if working with dependency list. The value of the ref will stay true after the first render. 

function Example() {
    const isStopped = React.useRef(false);
    const [text, setText] = React.useState("Please wait …");

    React.useEffect(() => {
        fetch();
        return () => {
          	isStopped.current = true;
        };
    }, []);

    function fetch() {
        simulateSlowNetworkRequest().then(() => {
            if (!isStopped.current) {
              	setText("OK!");
            }
        });
    }

    return <h2>{text}</h2>;
}

Summary

The best way to fix the error “Can’t perform a React state update on an unmounted component in React-hooks” is should not to update the state of a component after it has been unmounted. We always hope this information will help you. Please leave a comment below if you have any questions.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *