I have a component Example
in which I want to clear event listener when the local state display
changes to false,display
is set to true when show
prop is true and vice versa.
Code:
const Example = ({ show, onClose }) => {
const [display, setDisplay] = useState(false);
const handleClick = (e) => {
onClose();
console.log(display);
};
useEffect(() => {
if (display) {
document.addEventListener('click', handleClick);
} else {
document.removeEventListener('click', handleClick);
}
}, [display, handleClick]);
useEffect(() => {
if (show) {
setDisplay(show);
} else {
setDisplay(false);
}
}, [show]);
return <div>{display && <p>Hi</p>}</div>;
};
Issues:
- The component is unable to clear the event listener because a new reference of the function
handleClick()
is made every timeExample
renders. - Every time
handleClick()
is called, it logsdisplay
as true. - After 7-8 mouse clicks, the log count in console reaches to 7-8K.
What am I doing wrong here? Thanks :)