useClickOutside
Detects clicks outside of a referenced element.
Installation
Props
Prop | Type | Default | Description |
---|---|---|---|
ref | RefObject | null | The reference to the element to detect clicks outside of |
onClickOutside | function | null | The function to call when a click outside the element occurs |
Key Features & Details
Event Types & Capturing
- Listens for both
mousedown
andtouchstart
events to detect clicks and touches outside the referenced element. - Listeners are attached in the capturing phase (ensuring early detection before event bubbling).
Callback Reference
- The callback is always up-to-date using a ref, so you can safely use inline or dynamic functions without worrying about stale closures or unnecessary re-attachments.
Behavior
- The callback is only called if the event target is outside the referenced element.
- If the ref is
null
or the event target is not a DOM node, the callback is not called.
Cleanup
- Event listeners are automatically removed when the component unmounts.
Caveats & Best Practices
- Works for clicks/touches outside the referenced element, including those in React portals.
- Not suitable for server-side rendering (SSR) directly, as it uses
document
. - If you use multiple refs or dynamic elements, ensure the ref is stable and points to the correct element.
- The hook does not distinguish between left, right, or middle mouse buttons.
Examples
Basic Usage
const ref = useRef<HTMLDivElement>(null);
useClickOutside(ref, () => {
// Close dropdown or modal
});
return <div ref={ref}>Dropdown content</div>;
With Custom Component
const MyPopover = () => {
const ref = useRef<HTMLDivElement>(null);
useClickOutside(ref, () => {
// Hide popover
});
return <div ref={ref}>Popover content</div>;
};
Dynamic Callback
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useClickOutside(ref, () => setOpen(false));