I have a custom hook that handles clicks outside of a component:
const useOutsideClick = (ref, callback) => {
const handleClick = e => {
if (ref.current && !ref.current.contains(e.target)) {
callback();
}
};
useEffect(() => {
document.addEventListener("click", handleClick);
return () => {
document.removeEventListener("click", handleClick);
};
});
};
I have used this hook in a component like this:
const MyComponent = () => {
const container = useRef();
const [isOpen, setIsOpen] = useState(false);
useOutsideClick(container, () => {
console.log("clicked outside");
});
return (
<>
<span>another element</span>
<button onClick={() => setIsOpen(false)}>click</button>
<div ref={container}></div>
</>
);
};
The problem is when I click on the span, everything works fine. But, when I click on the button an it updates the state, it doesn't enter useOutsideClick callback function. How can I solve this problem?