Skip to content

Instantly share code, notes, and snippets.

@its-monotype
Created March 13, 2026 13:13
Show Gist options
  • Select an option

  • Save its-monotype/3a49eb13dd87439c435c90e90baa5297 to your computer and use it in GitHub Desktop.

Select an option

Save its-monotype/3a49eb13dd87439c435c90e90baa5297 to your computer and use it in GitHub Desktop.
React hook that detects pointer presses outside elements to close UI like dropdowns or popovers, listening on the document and using event.composedPath() so it works across portals and Shadow DOM where event.target can be misleading due to event retargeting.
import * as React from 'react';
export function useOutsidePress(
enabled: boolean,
refs: React.RefObject<HTMLElement | null>[],
onOutsidePress: () => void,
) {
const callbackRef = React.useRef(onOutsidePress);
React.useLayoutEffect(() => {
callbackRef.current = onOutsidePress;
});
React.useEffect(() => {
if (!enabled) return;
const handler = (event: PointerEvent) => {
const path = event.composedPath();
const isInside = refs.some(
(ref) => ref.current && path.includes(ref.current),
);
if (!isInside) callbackRef.current();
};
document.addEventListener('pointerdown', handler, true);
return () => document.removeEventListener('pointerdown', handler, true);
}, [enabled, refs]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment