Search code examples
javascriptreactjsevent-listenerlifecycle

Reactjs, removing event listener on componentWillUnmount,


I have a small react app. in One of my main components, I am adding an event listener on componentDidMount but when I try to remove it on componentWillUnmount it does not seem to be doing it. I have even tried putting them one after the other and still it does not seem to be removed.

Here is sample code of my situation (reduced from the real one)

listenerF(e){
  console.log('im scrolling!'
  //..actually does other stuff
}

componentDidMount(){
    window.addEventListener('scroll', e => this.listenerF(e))
}

componentWillUnmount(){
    window.removeEventListener('scroll',e=>this.listenerF(e))
    console.log('unmounted')
}

I suspect it might be the arrow function acting as an anonymous function, and therefore removeEventListener isn't matching the functions properly.

I tried some alternatives to add the event listener with just a function call or without an arrow function, but it didnt seem to work like that, so Im not sure what may be wrong with my syntax or setup that the event is getting added right, but cannot remove it


Solution

  • React injects the event to your handler automatically there is no need to wrap it in an arrow function just to pass the event, the problem is that React had no refference to the function that you passed to your handler.

    listenerF(e) { // dont forget to add the event as a parameter here
      console.log(e);
      console.log("im scrolling!");
    }
    
    componentDidMount() {
      window.addEventListener("scroll", this.listenerF);
    }
    
    componentWillUnmount() {
      window.removeEventListener("scroll", this.listenerF);
      console.log("unmounted");
    }