useOutsideClickRef
Returns a ref and calls a handler for click or touch-start events outside it.
About
useOutsideClickRef provides a callback ref and observes document-level clicks and touch starts outside its current element.
Example
import { useState } from "react";
import { useOutsideClickRef } from "rooks";
export default function DismissibleMenu() {
const [open, setOpen] = useState(true);
const [menuRef] = useOutsideClickRef(() => setOpen(false), open);
return (
<div>
<button onClick={() => setOpen(true)}>Open menu</button>
{open && (
<div ref={menuRef} role="menu" aria-label="Example menu">
Menu content
</div>
)}
</div>
);
}Parameters
handler(event): receives the nativeMouseEvent | TouchEvent.when: enables the document listeners; defaults totrue.
Return value
The hook returns a one-item tuple, [ref]. The callback ref accepts an HTMLElement | null.
Behavior and lifecycle
The hook stores the element assigned to the ref and registers capturing click and touchstart listeners on document. The handler runs only when a current element exists and does not contain the event target. Reassigning the ref updates the boundary. Disabling the hook or unmounting removes both listeners.
Compatibility and accessibility
No listeners are installed during server rendering. Provide explicit close and keyboard paths, manage focus for overlays, and restore focus to the trigger after dismissal.
Related
- useOutsideClick accepts an existing object ref.
- useKeyRef handles named keys on a callback-ref target.