Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React why should I remove event listeners?

Tags:

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?

like image 562
Mirror318 Avatar asked Nov 12 '18 06:11

Mirror318


People also ask

Why is it important to remove event listeners?

Removing the event listener from a specific HTML element can be so important in some cases as you don't want the event to get triggered multiple times without any reason.

What happens if you don't remove event listeners?

The main reason you should remove event listeners before destroying the component which added them is because once your component is gone, the function that should be executed when the event happens is gone as well (in most cases) so, if the element you bound the listener to outlasts the component, when the event ...

How do you clean up event listeners in react?

Add the event listener in the useEffect hook. Return a function from the useEffect hook. Use the removeEventListener method to remove the event listener when the component unmounts.

Can you remove event listeners?

Event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.


2 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 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

like image 173
SAMUEL Avatar answered Sep 21 '22 09:09

SAMUEL


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.

like image 42
Shubham Khatri Avatar answered Sep 21 '22 09:09

Shubham Khatri