ilokesto

useClickAway

useClickAway invokes a handler when a pointer or touch event occurs outside the referenced element. Ideal for closing popovers, dropdowns, and menus.

import { useRef } from 'react';
import { useClickAway } from '@ilokesto/utilinent/hooks';

function Menu() {
  const ref = useRef<HTMLDivElement>(null);
  useClickAway(ref, () => setOpen(false));
  return <div ref={ref}>{children}</div>;
}

Options

OptionDescription
ignoreAdditional refs whose contents are also considered "inside".
pointerEventsDetect pointerdown instead of mousedown/touchstart.

The handler receives the triggering event. SSR-safe: effects do not run on the server.

On this page