Skip to content

componentDidMount inside a class causing a memory leak #14630

Closed
@dorianrod

Description

@dorianrod

Hi,

I have a very weird memory leak that seems to be related to componentDidMount declaration. Memory is not freed after unmounting component.

Used code

Version: react 16.7
Mode: developper or production (same behaviour)

Here is the code I use to hide or display a list of items

class Item extends React.Component {
     componentDidMount() {

    }
      render() {
            return <div>test item</div>;
      }
}

class Items extends React.Component {
      constructor(props) {
            super(props);
            this.state =  {};
      }

      renderList() {
            let items = [];
            for(var i = 0; i < 4000; i++) {
                  items.push( <Item key={i} />);
            };

            return items;
      }

      onDisplay = ()=>{
            this.setState({display: true});
      }
      onHide = ()=>{
            this.setState({display: false});
      }

      render() {      
            return <div>
                  <div key="display" onClick={this.onDisplay}>Display</div>
                  <div key="hide" onClick={this.onHide}>Hide</div>
                  {this.state.display ? this.renderList() : null}
            </div>
      }
}
ReactDOM.render(<Items />, document.getElementById("app"));

Steps to reproduce

CASE 1
Use google chrome and display the performance monitor to study JS Heap size and Dom Nodes.

  1. Click on display => the list of 4000 items is displayed
  2. Click on "hide" => the list is unmounted
    When you look at performance monitor, you can see that around 8000 nodes are still in memory (and JS Heap is higher than before mounting components as well).
    If you redo 1) and 2) multiple times, you will see nodes going to 16000 then going back to 8000, ... etc.

Thus, memory is freed after the first unmount operation, but the first one is not. The weird thing is that if you do 1), 2), 2), 2), then it is freed.

CASE 2
Use the same code but remove the "componentDidMount" function in the class.
Do 1) and 2), then after few secondes memory is freed automatically (nodes and js heap) => expected behaviour

Behaviour expected

I was expected that the memory would be freed after unmounting a component, like in the 2nd case. That's a real issue when you mount.unmount big list multiple times, then js heap is going very high.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions