useOutsideClick
Calls a handler for click or touch-start events outside an object ref.
About
useOutsideClick observes document-level clicks and touch starts, then calls a handler when the event target is outside an element held by an object ref. It is commonly used to dismiss popovers and menus.
Example
import { useRef, useState } from "react";
import { useOutsideClick } from "rooks";
export default function DismissiblePanel() {
const panelRef = useRef<HTMLDivElement | null>(null);
const [open, setOpen] = useState(true);
useOutsideClick(panelRef, () => setOpen(false), open);
return (
<div>
<button onClick={() => setOpen(true)}>Open panel</button>
{open && (
<div ref={panelRef} role="dialog" aria-label="Example panel">
Click outside this panel to close it.
</div>
)}
</div>
);
}Parameters
ref: a mutable object ref whosecurrentvalue is anHTMLElement | null.handler(event): receives the nativeMouseEvent | TouchEvent.when: enables the listeners; defaults totrue.
Return value
The hook returns void.
Behavior and lifecycle
The hook registers capturing click and touchstart listeners on document. It calls the handler only when ref.current exists and does not contain the event target. The current handler is retained through a ref. Disabling the hook or unmounting removes both listeners.
Compatibility and accessibility
No listeners are installed during server rendering. Outside-click dismissal must not be the only close path: provide a visible close button, Escape-key handling, sensible focus placement, and focus restoration for dialogs and menus.
Related
- useOutsideClickRef creates the callback ref for you.
- useKey can add Escape-key dismissal.