Close menus or popovers when a click happens outside a ref.
Section: Common UI Hooks
Handle clicks outside an element
tsx
tsx
function useOnClickOutside<T extends HTMLElement>(ref: React.RefObject<T>, onOutside: () => void) {
useEffect(() => {
function handle(event: MouseEvent) {
if (!ref.current || ref.current.contains(event.target as Node)) return;
onOutside();
}
document.addEventListener('mousedown', handle);
return () => document.removeEventListener('mousedown', handle);
}, [ref, onOutside]);
}Explanation
Common for menus, dialogs, tooltips, and dropdowns.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing Common UI Hooks