How to handle memory leak in react native

What is a memory leak in react native

Here we are going to discuss the “”How to handle memory leak in react native“, when we start the API integration in our app, then we all find the a common issue every time which is ” 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“.

Issue is like –

https://www.itechinsiders.com/ - react native memory leak

Intro: 

This is happening because of memory leak, when we go to another screen then it must stop API calling on this page, so let’s start how to handle this issue.

Step1: 

Firstly we need to declare a global variable for unsubscribe API calling, which is boolean type.

_isUnsubscribeApi = false;

Step2: 

Now we make this variable true in componentDidMount then place the API call, always prefer to call API at componentDidMount because componentWillMount removed.

componentDidMount() {
  this._isUnsubscribeApi= true;
   if (this._isUnsubscribeApi == true) {
    setTimeout(() => {
     this.gettingQuestionsWithAnswers();//this is a function where we 
     call API
    }, 100);
   }
  }
}

Step3: 

Make this variable false in unmount lifecycle, so it calls only that page.

componentWillUnmount() {
 this._isUnsubscribeApi= false;
}

So the topic  “How to handle memory leak in react native” is completed, you can find the next lesson here.

And you can find my post on medium as well click here please follow me on medium as well.

And if any other query/issue, please feel free to ask.

Happy Coding Guyz.

Related Post

Leave a Reply

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