React / componentWillUnmount() - what does it actually do?

Spoiler alert: this post contains answers to React: Add Event Listeners

According to the page explanation,

        document.removeEventListener("keydown", this.handleKeyPress)

will remove the event listener previously attached in

        document.addEventListener("keydown", this.handleKeyPress)

I thought that this would mean the event would only fire only once, but if I continuously press on the ‘Enter’ key, the message prints out each time: You pressed the enter keyYou pressed the enter keyYou pressed the enter key, etc, etc.

Could any one explain, in the simplest possible English :),

  1. why we would want to remove the event listener and
  2. what actually happens in the browser (if anything) when we do?


componentWillUnmount will only be called when the component is destroyed, that means only when the component is removed from the page.

Imagine that you have two tabs, each one will a list inside it. When you change from the first to the second tab the list in the first will be destroyed, and if it has a componentWillUnmount it will be called.

Regarding why we would want to remove the listener, if the component is destroyed we don’t want to have a event emitter keeping a reference to it. This is due to two reasons:

  • If the event emitter keeps the reference the component won’t ge garbage collected, and will waste memory. This may be a big problem in larger apps.
  • Events may be triggered after the component is destroyed, which may cause runtime errors.

Hope it helps!

That helped a lot - thanks very much! :slight_smile: