Search code examples
reactjsmemory-leaksfetchreact-component-unmount

Memory leak error while calling fetch API in react


I have following code written in react and I am get memory leak error. I tried few hacks like calling abort and setting the state to null but nothing worked for me so far.

Error I am getting:

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 use Effect cleanup function.

My code snippet:

useEffect(() => {
    //some const defined
    fetch(myData)
        .then(response => response.json())
        .then(data => {
            //some code

            if (consition) {
                //setting state
                setData(abc);
                setDataPresent(true);
            }
        });
    // fix for memory leak error
    return () => {
        setData({});
        setDataPresent(false);
    };
}, [dep]);

Solution

  • Try this! You need to cancel the promise with useEffect.

    In the code below, the fetch function returns a promise. You can cancel the promise by having a conditional in the scope of useEffect, preventing the app from setting state after the component has unmounted.

    I recommend reading this short article on canceling promises in useEffect. https://juliangaramendy.dev/blog/use-promise-subscription

    Don't forget about dependencies in useEffect.

    // Let's start!
    useEffect(() => {
        let isMounted = true;
    
        fetch(myData)
            .then(response => response.json())
            .then(data => {
                if (isMounted) {
                    setDataPresent(true)
                    setData(abc)
                }
            });
    
        return () => {
            isMounted = false;
        };
    }, [deps]);