How to handle memory leak in react js

How to handle memory leak in react js

Sometimes you are getting warning message like

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.


memory-leak-react-js

When we go to other screens then it must stop API calling of this page.

Step 1: we declare a global variable in the component
isStopApiCalling=false;

Now we make this variable true in componentDidMount after that you can call API.

componentDidMount() {
this.isStopApiCalling=true;
if(this.isStopApiCalling == true)
{
  this.calledAPIFunction(); // this is a function to call API
}
}

Step 3: Make this variable false in the unmount lifecycle.

componentWillUnmount() {
this.isStopApiCalling = false;
}


I hope it can help you.

Comments