JAVASCRIPT
React useClickOutside Hook for Dismissing UI Elements
Detect clicks outside a specified DOM element in React, perfect for closing dropdowns, modals, or context menus when users click away.
import { useEffect } from 'react';
function useClickOutside(ref, handler) {
useEffect(() => {
const listener = (event) => {
// Do nothing if clicking ref's element or descendant elements
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]); // Reload only if ref or handler changes
}
How it works: This `useClickOutside` hook executes a provided `handler` function when a click or touch event occurs *outside* of the `ref`'s element. It's invaluable for UI components like dropdowns, popovers, or modal dialogs that need to be dismissed when the user interacts with other parts of the page. The hook gracefully handles both mouse and touch events and cleans up its listeners on unmount.