1
 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");) ?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
R. Kohlisch
  • 2,823
  • 6
  • 29
  • 59

2 Answers2

1

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);
Gena Moroz
  • 929
  • 5
  • 9
1

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

gdh
  • 13,114
  • 2
  • 16
  • 28
  • hi - hope the answer was useful... do you have any follow up question on this.? – gdh May 20 '20 at 08:53