Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing Event Listener - Do I need to pass the exact same anonymous function?

 componentDidMount() {
    window.addEventListener("scroll", (e) => {console.log("Hello"});
  }

 componentWillUnmount() {
    window.removeEventListener("scroll", (e) => {console.log("Hello"});
  }

...do I really need to do window.removeEventListener("scroll", (e) => {console.log("Hello")});?

Or can I just do window.removeEventListener("scroll", ()=> {}); (with an empty function)? I don't understand why, when removing the eventListener, I need to pass it the exact same anonymous function?

what if I do window.removeEventListener("scroll", ()=> {console.log("Hello2")}); - is this considered a new function now? So will this not remove the original event listener (which has console.log("Hello");) ?

like image 512
R. Kohlisch Avatar asked Jan 22 '26 21:01

R. Kohlisch


2 Answers

Yes, you have to pass exact same reference, since function is an object and variable holding a reference and function(){} is not equals function(){}

function stuff(){/* your stuff;*/}
window.addEventListener("event",stuff);
window.removeEventListener("event",stuff);
like image 187
Gena Moroz Avatar answered Jan 25 '26 10:01

Gena Moroz


Your componentWillUnmount function will not remove event listener because the function reference of the event listener which was attached in componentDidMount is not the same as the one it(compWillUnmount) is trying to remove.

You can check it out by creating and comparing 2 functions in chrome console.

enter image description here

In general, define the eventListener function in your class and attach it in componentDidMount and remove it in componentWillUnmount. Since they are executed once, the function reference remains same.

class MyComponent extends React.Component {
 ...
 myEventFun = (e) => {console.log("Hello")};

 componentDidMount() {

    window.addEventListener("scroll", this.myEventFun);
  }

 componentWillUnmount() {
    window.removeEventListener("scroll", this.myEventFun);
  }
...

If you want to deal with adding/removing event listeners in functional component, see this and this

like image 22
gdh Avatar answered Jan 25 '26 12:01

gdh