JAVASCRIPT
Custom useOnClickOutside Hook for React Components
Detect clicks outside of a specific React component with this custom hook. Perfect for closing modals, dropdowns, or tooltips when a user clicks elsewhere on the page.
import { useEffect, useRef } from 'react';
function useOnClickOutside(ref, handler) {
useEffect(() => {
const listener = (event) => {
if (!ref.current || ref.current.contains(event.target)) {
return;
}
handler(event);
};
document.addEventListener('mousedown', listener);
document.addEventListener('touchstart', listener);
return () => {
document.removeEventListener('mousedown', listener);
document.removeEventListener('touchstart', listener);
};
}, [ref, handler]);
}
How it works: The `useOnClickOutside` hook allows you to detect clicks or touches that occur outside a referenced DOM element. It attaches event listeners to the `document` when the component mounts. If a click/touch event occurs and the target is not within the provided `ref` element, the `handler` function is called. The listeners are cleaned up when the component unmounts.