Haekal Dinova
Haekal Dinova

Reputation: 3

Can't remove event listener in react application

So there is a function that looks like this

function eventListener(e) {
    if (!modalRef.current.contains(e.target)) {
      setOpenModal(false);
    }
  }

And i add an event listener to listen for event bubbles to the body on startup

 useEffect(() => {
    document.body.addEventListener("click", eventListener, true);
    return () => {
      document.body.removeEventListener("click", eventListener, true);
    };
  }, []);

And when the component is listening to the bubble state

 useDidMountEffect(() => {
    console.log("hello the buble is", buble);
    if (buble) {
      document.body.addEventListener("click", eventListener, true);
    } else {
      console.log("I'm in false mode");
      document.body.removeEventListener("click", eventListener, true);
    }
  }, [buble]);

But sadly can't remove it prove it's not removing

I have read these websites

  1. https://www.edureka.co/community/71646/find-event-listeners-node-when-debugging-from-javascript-code

  2. Can't remove all event listeners

i have also use the arrow function but it didn't work. And also the useDidMountEffect is a custom hook so that the function doesn't run on startup but when i mount it

Upvotes: 0

Views: 386

Answers (1)

Yura Synkulych
Yura Synkulych

Reputation: 23

You must wrap your eventListener function to useCallBack with empty array of dependency.

const eventListener = useCallback(function (e) {
  if (!modalRef.current.contains(e.target)) {
    setOpenModal(false);
  }
}, []);

Upvotes: 1

Related Questions