Search code examples
reactjsuse-effectuse-state

Event Listener is not removing


I am trying to remove the Event Listener that i created but unable to do that, don't know where I am going wrong. Any help is highly appreciated.

const [windowEvent, setWindowEvent] = useState(false);

function handleClick(){
  alert("Mouse Pressed!!");
}

useEffect(function(){

  if(!windowEvent){
    window.removeEventListener("dblclick",handleClick);
  }
  else{
    window.addEventListener("dblclick",handleClick);
  }
},[windowEvent]);
return (
  <div>
    <button onClick={() => setWindowEvent(prevState => !prevState)}>Toggle Window Event</button>
    {windowEvent && <WindowEvent />}
  </div>
)

Solution

  • If your Effect subscribes to something, you need a cleanup function that should unsubscribe.

      useEffect(
        function () {
          if (windowEvent) {
            window.addEventListener("dblclick", handleClick);
          } 
    
          return () => window.removeEventListener("dblclick", handleClick);
        },
        [windowEvent]
      );
    

    React beta docs explains clearly how to subscribe to events

    Edit Removed useless else statement