React: Custom Hook to Close a Menu on Outside Click
Closing a menu when you click outside it can be packaged as a custom hook. The hook waits for pointerdown on document and checks whether the pressed element is inside the menu. The component using it needs one line that passes the refs of the elements to treat as inside and the close function.
There are three things to watch for when writing this hook: include the open button as an inside element, wait for pointerdown instead of click, and treat parts rendered elsewhere through a portal as inside. For each one, I compared the behavior with a version that didn't do it.
The test environment was Ubuntu 24.04, Node.js 22.22.0, and Chrome for Testing 153. I used react / react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, esbuild 0.28.2, and Playwright 1.56.1. I type-checked the .tsx with tsc, transformed it with esbuild, and ran it in the browser operated by Playwright. Only the StrictMode check used a development build; everything else used a production build. Touch was reproduced with tap on a touch-enabled page in Playwright, and I did not test on a real device. I did not test Firefox, Safari, or clicks inside an iframe.
The whole hook
The hook takes three arguments: an array of refs to the elements that count as inside, the function to call when an outside press happens, and a flag that controls whether the hook is active.
import { useEffect, useEffectEvent, type RefObject } from 'react';
// Calls onOutside when a press lands outside every element in targets. Does nothing while enabled is false
export function useClickOutside(
targets: RefObject<HTMLElement | null>[],
onOutside: (event: PointerEvent) => void,
enabled = true,
) {
// Even if the caller passes a new function or array on every render, the listener is not re-registered
const onPointerDown = useEffectEvent((event: PointerEvent) => {
const node = event.target as Node;
if (targets.some((target) => target.current?.contains(node))) return;
onOutside(event);
});
useEffect(() => {
if (!enabled) return;
document.addEventListener('pointerdown', onPointerDown);
return () => document.removeEventListener('pointerdown', onPointerDown);
}, [enabled]);
}
Whether an element is inside is decided by whether the pressed element is the ref's element itself or one of its descendants, as described on MDN's Node.contains() page.
The body of the listener is wrapped in useEffectEvent. This follows the same pattern as the useEffectEvent reference example that reads the latest values in an event listener. The caller creates a new array like [menuRef, buttonRef] or a new function like () => setOpen(false) on each render, but since these are not in the dependency array, the listener isn't removed and re-added every time.
Using it in a menu
The hook is active only while the menu is open, and it closes the menu when an outside press happens.
function Menu() {
const [open, setOpen] = useState(false);
const menuRef = useRef<HTMLDivElement>(null);
const buttonRef = useRef<HTMLButtonElement>(null);
useClickOutside([menuRef, buttonRef], () => setOpen(false), open);
return (
<>
<button ref={buttonRef} onClick={() => setOpen((o) => !o)}>メニュー</button>
{open && (
<div ref={menuRef} className="menu">
<p>並べ替え</p>
<button>名前順</button>
</div>
)}
</>
);
}
I displayed this Menu in the browser and performed these actions in order: open it, press an item inside the menu, press outside, open it again, and press the button while it is open.
ボタンを押したあと: メニューが出ている
メニューの項目を押したあと: メニューが出ている
外側(左上から 400,300 の位置)を押したあと: メニューが出ていない
もう一度ボタンを押したあと: メニューが出ている
開いたままボタンを押したあと: メニューが出ていない

Include the open button as well
I also tested a version where the open button was not in targets and only the menu was treated as inside. When the menu is open and the button is pressed, it does not close and stays open.
もう一度ボタンを押したあと: メニュー:開いている
開いたままボタンを押したあと: メニュー:開いている
呼ばれた順: toggle → outside → toggle → outside → toggle
In the last action, the hook judged the button to be outside at the pointerdown when the button was pressed, and closed the menu. Then, when the mouse button was released, the click ran the button's onClick, which toggles the state, so the menu opened again. When the button is included as an inside element, the last button press only calls toggle, and the menu closes.
Wait for pointerdown instead of click
In a version where the hook listened to click instead of pointerdown, I ran into two problems.
The first problem: if the button is not included as an inside element, the click that opens the menu closes it right away.
ボタンを押したあと: メニュー:閉じている
呼ばれた順: toggle → outside
document のリスナー: add click, remove click
The click listener was attached to document during the click that opened the menu, and the same click closed it. The React 18 changelog says that effects from updates caused by clicks and key presses run synchronously. The likely cause is that after the button's onClick opens the menu, the effect runs inside that same click handling and attaches the listener before the click reaches document. With the pointerdown version, the listener is also attached within the same click's handling, but that press's pointerdown has already finished. Even the version that did not include the button didn't close on the opening press (in the previous section's version, the menu stayed open after pressing the button).
The second problem: pressing the mouse button on text inside the menu, dragging outside, and releasing closes the menu. Merely trying to select text makes the menu disappear.
click: メニュー:閉じている
fixed: メニュー:開いている
The first line is the click-based version, and the second line is the hook in this article. According to the MDN click event page, when the press and release happen on different elements, the click is dispatched to the nearest common ancestor of both. That ancestor is outside the menu, so the click-based version treated it as an outside click. With pointerdown, the check uses the element at the moment of pressing, so a press started inside the menu stays inside.
Attach the listener only while open
Since open is passed as enabled, there is no listener on document while the menu is closed. I counted the listener adds and removes. It was attached once when the menu opened, stayed attached while it was open even after re-rendering the component using the hook 5 times, and was removed once when the menu closed. Wrapping it in StrictMode in a development build gave the same result.
StrictMode あり(開発用のビルド)
表示した直後: (なし)
開いたあと: add pointerdown
開いたまま 描き直し 5回 のあと: add pointerdown
閉じたあと: add pointerdown, remove pointerdown
In StrictMode, during development only, the effect setup and cleanup run one extra time right after mounting (useEffect reference caveats). Right after mounting, the menu is closed and open is false, so no listener is attached at that point. For comparison, when I mounted a version that omits enabled and is active from the start, in StrictMode it attached, removed, and attached again. Because the cleanup removes the listener, there were never two listeners left behind.
表示した直後: add pointerdown, remove pointerdown, add pointerdown
Inside a portal counts as outside in the DOM
I placed a "Choose a color" button inside the menu and rendered the color list to body with createPortal. The color list's elements are outside the menu's element, so in the version that only uses contains, the menu closes the moment a color in the list is pressed. Because the list disappears when the menu closes, no color was selected.
色の一覧の DOM の親: BODY/メニューの要素の中にあるか: false
「白」を押したあと: メニュー:閉じている/色:なし
As the createPortal reference caveats explain, events inside a portal propagate along the React tree, not the DOM. So I made a version where onPointerDownCapture on the menu element records the press event as one that happened inside, and the document listener reads that record.
import { useEffect, useEffectEvent, useRef, type RefObject, type PointerEvent as ReactPointerEvent } from 'react';
// A version of useClickOutside that also treats presses inside a portal as inside
export function useClickOutside(
targets: RefObject<HTMLElement | null>[],
onOutside: (event: PointerEvent) => void,
enabled = true,
) {
// Keep track of presses that happened inside the React tree
const insideEvents = useRef(new WeakSet<Event>());
const onPointerDown = useEffectEvent((event: PointerEvent) => {
if (insideEvents.current.has(event)) return;
const node = event.target as Node;
if (targets.some((target) => target.current?.contains(node))) return;
onOutside(event);
});
useEffect(() => {
if (!enabled) return;
document.addEventListener('pointerdown', onPointerDown);
return () => document.removeEventListener('pointerdown', onPointerDown);
}, [enabled]);
// Pass this to the onPointerDownCapture of an inside element. It is also called for presses inside a portal
return (event: ReactPointerEvent) => {
insideEvents.current.add(event.nativeEvent);
};
}
On the calling side, pass the returned function to the menu element.
const markInside = useClickOutside([menuRef, buttonRef], close, open);
// ...
<div ref={menuRef} className="menu" onPointerDownCapture={markInside}>
event.nativeEvent is the original browser event (React's event object description). The same page says React attaches its event handlers to the root. The root element is inside document, so React's handler runs before the document listener, and it adds the press event (event.nativeEvent) to insideEvents. The document listener then checks it afterward, so it can tell that the press happened inside. In the test, pressing white in the color list kept the menu open, and the color was selected.
「白」を押したあと: メニュー:開いている/色:白
外側を押したあと: メニュー:閉じている/色:白
Closing with touch too
As the MDN pointerdown event page describes, pointerdown fires for mouse button presses as well as when a finger touches the screen. On a touch-enabled page, tapping an item left the menu open, and tapping outside closed it. When tapping outside, pointerdown arrived first.
ボタンをタップしたあと: メニュー:開いている
メニューの項目をタップしたあと: メニュー:開いている
外側をタップしたあと: メニュー:閉じている
外側のタップで届いたイベント: pointerdown(touch) → touchstart → mousedown → click
Key points when building it
A hook that closes on outside clicks looks at the element pressed by a pointerdown listener on document, and uses contains on the ref's element to decide whether it is inside. Include the open button as an inside element, and wait for pointerdown instead of click. This avoids both the problem of closing on the opening click and the problem of closing while selecting text. When part of the UI is rendered elsewhere with a portal, use onPointerDownCapture, which follows the React tree, to record the press as inside.
If the menu is the only thing you need, you could also consider the Popover API, which lets the browser handle closing on outside clicks and the Esc key. I covered it in an earlier article, "How to Show a Menu with the Popover API in React."





