Skip to main content

useClickOutside

The useClickOutside hook detects when a user clicks or touches outside of a specified element and executes a callback function. This is commonly used for closing dropdowns, modals, and other overlay components.

Installation

Import

Usage

Parameters

RefObject<T>
required
A React ref object pointing to the element to detect outside clicks for. The hook will ignore clicks on this element and its descendants.
(event: MouseEvent | TouchEvent) => void
required
A callback function that will be called when a click or touch event occurs outside the referenced element.

Type Definition

Examples

Context Menu

Popover Component

Search with Suggestions

Common Patterns

Conditional Handler

Only close when a specific condition is met:

Multiple Refs

Handle clicks outside multiple elements:

Notes

  • The hook listens to both mousedown and touchstart events for better mobile support
  • Clicks on the referenced element and all its descendants are ignored
  • The event listeners are automatically cleaned up when the component unmounts
  • Make sure the ref is attached to a DOM element, not a React component