useClickOutside
Listen for clicks outside of an element. Useful for modal or dropdown
useClickOutside detects clicks (mouse and touch events) that occur outside of a referenced DOM element and invokes a callback when they happen. Pass a ref to the target element, a handler function, and an optional enabled boolean to conditionally toggle the listener. The handler receives the original MouseEvent or TouchEvent.
When to Use
- Closing dropdown menus, popovers, or modals when the user clicks outside of them
- Deselecting or deactivating an inline editing component when focus moves away
- Dismissing notification toasts or context menus on outside interaction
Notes
- Event types: Listens for both
mousedownandtouchstartevents, covering desktop and mobile interactions. - Cleanup: The event listeners are automatically removed when the component unmounts or when
enabledis set tofalse. - Also available as
useClickAway, which is an alias with the identical API and implementation.
Usage
Live Editor
function Demo() { const [visible, setVisible] = useState(false); const modalRef = useRef<HTMLDivElement>(null); useClickOutside(modalRef, () => { setVisible(false); }); return ( <div> <button onClick={() => setVisible(true)}> Open Modal</button> {visible && ( <div ref={modalRef} style={{ position: "fixed", left: "50%", top: "50%", transform: "translate(-50%,-50%)", width: 420, maxWidth: "100%", zIndex: 10, border: "1px solid var(--c-input-border)", background: "var(--c-bg)", }} > <div style={{ padding: "0.4em 2em", boxShadow: "2px 2px 10px var(--c-box-shadow)", }} > <p style={{ fontWeight: 700, fontSize: "1.4rem", marginBottom: "2rem", }} > Demo Modal </p> <p>Click outside of the modal to close it.</p> </div> </div> )} </div> ); };
Result
API
useClickOutside
Returns
void
Arguments
| Argument | Description | Type | DefaultValue |
|---|---|---|---|
| target | dom element | BasicTarget<Element> (Required) | - |
| handler | listener fucntion | (evt: EventType) => void (Required) | - |
| enabled | whether the listener fucntion is enabled | boolean | undefined | - |
BasicTarget
export type BasicTarget<T extends TargetType = Element> = (() => TargetValue<T>) | TargetValue<T> | MutableRefObject<TargetValue<T>>;
TargetValue
type TargetValue<T> = T | undefined | null;
TargetType
type TargetType = HTMLElement | Element | Window | Document | EventTarget;
EventType
export type EventType = MouseEvent | TouchEvent;