React why should I remove event listeners?

Viewed 8589

I see a lot of code like this:

componentDidMount() {
  // add event listener
}

componentWillUnmount() {
  // remove event listener
}

I understand if the listener is set on something global like window, but if it's just on an HTML element within the component that's about to be unmounted, won't the listener disappear with the component anyway?

3 Answers

The event listeners need to be removed due to following reason.

  • Avoid memory leaks, if the browser is not handled it properly.Modern browsers will garbage collect event handlers of removed DOM elements but it is not true in cases of legacy browses like IE which will create memory leaks.
  • Avoid collisions of events of components.
  • Remove the side effects when the reference are stored in some persistence such as local storage

Here is a good article to get an insights on event listners

Modern browsers do remove event listeners on components when they are unmounted, however for some reason if you store the reference of this node in any other component that is not mounted or in localStorage, Garbage collector will not be able process this and it can potentially cause memory leaks.

Hence, the safest way to handle such scenarios is to manually remove event listeners in componentWillUnmount.

P.S. With hooks, react provides way to return a function which can be used to remove listeners in the useEffect hook.

If event listeners are not removed, it will cause memory leak for older browsers (IE 6 and 7, if i recall correctly). Hence will cause unnecessarily high memory utilization which will lead to many problems. Also, in this case, you will have issues with debugging as in a big project you never have control of the entire codebase and you can have multiple references of same component loaded from different components and if memory leak is not handled by the browser, then it will create a lot of confusion regarding the triggered events.

Related