Docs
useClickOutside

useClickOutside

Detects clicks outside an element and fires a callback. Useful for closing menus, dropdowns, modals and popovers when the user interacts with any area outside the component.

The hook listens for mousedown in the capture phase on document and fires the callback whenever the event target is not contained in the referenced element.

When to use

✅ Use when…🚫 Avoid when…
  • To close dropdowns/popovers on a click anywhere outside the menu.
  • In lightweight modals without an overlay, where "outside" is any area of the page.
  • In inline editors that need to confirm/cancel when focus leaves.
  • To detect keyboard focus loss (use onBlur or focusin/focusout).
  • In layers that must only close through an explicit action (e.g. a button).
  • As a replacement for an accessible modal's focus trap — this hook complements it, it does not replace it.

Signature

const ref = useClickOutside<T extends HTMLElement>(callback: () => void);

Example

import { useClickOutside } from '@apollion-dsi/core/hooks';
 
function Dropdown({ onClose }: { onClose: () => void }) {
  const ref = useClickOutside<HTMLDivElement>(onClose);
 
  return (
    <div ref={ref}>
      <p>menu content</p>
    </div>
  );
}

See also