1

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]);
Ivan Popov
  • 656
  • 2
  • 10
Eric
  • 123
  • 9

1 Answers1

0

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]);
Ivan Popov
  • 656
  • 2
  • 10
  • Thanks @Ivan Popov for the solution. It works for me though now but since the leak issue do not generate more often, I need to wait and see for some more time. But for now it works, thanks. – Eric Oct 10 '21 at 19:04
  • @coder91, I am always happy to help. If there are similar situations where the promise will be used in the effect, then create a hook. You can also use the hook implementation from the article I gave the link to. Happy coding!) – Ivan Popov Oct 10 '21 at 19:39