Reputation: 3
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
https://www.edureka.co/community/71646/find-event-listeners-node-when-debugging-from-javascript-code
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
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