4
votes

The state in my React component does not get garbage collected when the component is dismounted, causing memory leak. I am using [email protected] on Chrome 10.12.5 on macOS Sierra.

I am setting a state in componentDidMount like this.

To confirm the memory leak, I have added the following to my componentDidMount:

let arr = new Uint8Array(1024 * 1024 * 30);
this.setState({
  test: arr
});

and took a heap snapshot to confirm 30MB of Uint8Array allocated on heap.

Then, I have confirmed that the component gets dismounted by console.log in componentWillUnmount.

When I take a heap snapshot afterwards, even after allowing ample time for garbage collection to happen, Uint8Array remains in the heap.

Any ideas about where to start debugging this issue? Or any observation from the source code?

1
Might be the case that the actual JS object representing the component and its state isn't being removed, even if the component is removed from the DOM. Perhaps React caches it for later reuse? Might be worthwhile to raise a bug with React.Horia Coman
I saw in that github link you posted that you're calling window.addEventListener . Are you also removing that event listener? That could cause memory leaks. I just glanced at your problem so I apologize if i'm totally off there.Rico Kahler
@RicoKahler I am removing that listener. I think it is a separate problem, because the problem at hand is that the state object is not being garbage collected.Sung Cho

1 Answers

0
votes

In my understanding you are expecting that componentWillUnmount works as a class destructor, but I think that React component lifecycle works in a different manner.

Object's properties like the state are commonly inited in the class constructor, then componentWillMount/componentDidMount and componentWillUnmount simply works with the same object.

If the component is not in the DOM anymore does not mean it's garbage collected. The same object will be used when (if) you re-mount it.

You can probably empty clean state yourself in componentWillUnmount if it make any sense for you. In this case I think GC will recover the memory.