Skip to main content

useClickOutside

Location: src/hooks/useClickOutside.js

Overview

A utility hook that detects clicks (or taps) outside a referenced DOM element. Commonly used to close dropdowns, modals, popovers, and context menus when the user interacts outside them. Listens for both mousedown and touchstart events on the document.

Signature

function useClickOutside(
onClickOutside: (event: MouseEvent | TouchEvent) => void,
enabled?: boolean
): React.RefObject<HTMLElement>

Parameters

ParameterTypeRequiredDescription
onClickOutside(event: MouseEvent | TouchEvent) => voidYesCallback invoked when a click or touch occurs outside the referenced element. Receives the original DOM event.
enabledbooleanNoWhether the listener is active. Defaults to true. Set to false to temporarily disable detection.

Return Value

PropertyTypeDescription
refReact.RefObject<HTMLElement>A ref object to attach to the element you want to monitor. Clicks outside this element trigger the callback.

Usage

function Dropdown({ onClose }) {
const ref = useClickOutside(() => {
onClose();
});

return (
<div ref={ref} className="dropdown">
<p>Dropdown content</p>
</div>
);
}

With enabled toggle

function Popover({ isOpen, onClose }) {
const ref = useClickOutside(onClose, isOpen);

if (!isOpen) return null;

return (
<div ref={ref} className="popover">
<p>Popover content</p>
</div>
);
}

Last updated: 2026-02-07