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?
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.
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 ...
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.
Event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.
The event listeners need to be removed due to following reason.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With