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

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

hi - hope the answer was useful... do you have any follow up question on this.?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.