How to find out memory leaks in react native app?

16,110

Solution 1

I had the same issue, few methods that helped were:

Using transform-remove-console:

https://www.npmjs.com/package/babel-plugin-transform-remove-console

add this to your babel production plugins and install it. It will hide all the console logs in the app in production.

Adding a mounted state

Specifically, calling setState() in an unmounted component means that your app is still holding a reference to the component after the component has been unmounted - which often indicates a memory leak!

https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html

import React, { Component } from 'react';


class App extends Component {

  _isMounted = false;

  componentDidMount() {
    this._isMounted = true;
    // ... do your stuff here
  }

  componentWillUnmount() {
    // tells the component that component is now unmounted
    this._isMounted = false;
  }

  getUsersFromApi(){
    if(this._isMounted){
      // ... tasks
    }
  }

}

export default App;

Solution 2

I too had the same issue, because of calling setState on an unmounted component,

So, I usually have this template for any class-based component that has a state:

I forgot about setState(), and use setComponentState declared down:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      // other fields...

    };
    this.isUnmounted =  true,
  }

  componentDidMount(){
      this.isUnmounted =  false;
  }

  componentWillUnmount() {
      this.isUnmounted = true;
  }

  setComponentState = (values) => {
    if (!this.isUnmounted) this.setState(values);
  };
}
Share:
16,110
Linu Sherin
Author by

Linu Sherin

React Native Developer

Updated on June 08, 2022

Comments

  • Linu Sherin
    Linu Sherin almost 2 years

    I've build a learning management system app in react native android.I'm using AsyncStorage for simple state management and not used redux at all.The issue I'm facing now is if I'm going to use the app continuously by performing different actions then the app become very slow.I think it is memory leak because when I kill the app from background and open it again it is working without any delay.So I don't know how to avoid this memory leak.I've tried many solutions

    1. Removed all console.log from app
    2. Changed all inline styles
    3. Used ComponentDidMount instead of ComponentWillMount.
    4. Tried prefetching of data.

    But I don't know how remove data from heap memory.Is the data is getting stored within heapon each navigation?So this will makes the app very slow in performance. I don't know whether I'm right.Excuse me if there is any mistake in my concept.There is no time to change the state management to redux now.Anybody please help me to find a solution , it will be a great help.Thank you!

  • Linu Sherin
    Linu Sherin about 5 years
    I've tried both the methods.But still the response is same