React Hooks Can't perform a React state update on an unmounted component in React JS

By Super Admin | Oct 22, 2021 | React JS
Share : Whatsapp

https://www.fundaofwebit.com/post/react-hooks-cant-perform-a-react-state-update-on-an-unmounted-component

React Hooks Can't perform a React state update on an unmounted component in React JS


Error:

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 a useEffect cleanup function.

The solution is to use a local variable that keeps track of whether the component is mounted or not. This is a common pattern with the class based approach.

Here is an example given below with Product Component, where we create a isMounted variable with the initial value of false. The useEffect() hook is called when the component is mounted and sets the isMounted current variable value to true. The return function from the useEffect() hook is called when the component is unmounted and sets the isMounted current variable value to false.


import React, {useState, useEffect} from 'react';
import axios from 'axios';

function Products()
{
    const [products, setProducts] = useState([]);

    useEffect(() => {
       
        let isMounted = true;
       
        axios.get(`/api/products`).then(res=>{

            if(isMounted)
            {
                if(res.data.status === 200)
                {
                    setProducts(res.data.products);
                }
            }
        });

        return () => {
            isMounted = false
        };

    }, []);
}

export default Products;


Hope this helps you.

Thanks for reading.