Skip to main content
Version: 5.3.2

useOutsideClick

The useOutsideClick hook allows you to detect clicks that occur outside a specific DOM element, triggering a callback function when this happens.
It’s ideal for closing modals, dropdowns, tooltips, or any component that should dismiss when clicking elsewhere on the page.

Syntax

useOutsideClick(
ref: RefObject<HTMLElement>,
callback: (event: MouseEvent | TouchEvent) => void,
deps?: DependencyList
): void;

Parameters

NameTypeDescription
Refs (required)RefObject<HTMLElement>React ref to the element to detect outside clicks from
Callback (required)(event: MouseEvent or TouchEvent) => voidFunction to run when an outside click is detected.
deps (optional)DependencyListDependency array for when to refresh the callback behavior

Example

It listens for clicks outside the box and automatically hides it whenever you click anywhere else on the page.

Preview