score:25

Accepted answer

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 of event listeners are stored in some persistence such as local storage or some thing like this

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

score:1

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.

score:11

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.


Related Query

More Query from same tag