Skip to the content

useClickOutside

useClickOutside calls a function when the user presses the mouse outside an element. Use it to close a custom menu or panel on an outside click.
Hooks

Signature

const ref = useClickOutside<T extends HTMLElement>(callback: () => void);
Name
Type
Description
callback
() => void
Runs on every mousedown whose target is outside the referenced element.
returns
RefObject<T>
Attach it to the element to protect.
Scrolls sideways inside the table. The page does not.

Example

import { useClickOutside } from '@apollion-dsi/core/hooks';

function Menu({ onClose }: { onClose: () => void }) {
  const ref = useClickOutside<HTMLDivElement>(onClose);

  return <div ref={ref}>menu content</div>;
}

Pitfalls

  • It listens to mousedown on document in the capture phase. Keyboard focus leaving the element does not trigger it — handle Escape and blur yourself.
  • The listener stays attached for the component's whole life. Mount the hook only while the panel is open, or guard the callback, or it fires on every click on the page.
  • A click inside a portal (a tooltip, a dropdown menu) counts as outside, because the portal is not a DOM descendant.

See also