Skip to Content
HooksuseClickOutside

useClickOutside

useClickOutside helps you close menus, popovers, drawers, and other dismissable UI when an interaction happens outside the monitored element.

Live Example

Dismissable panel

This demo shows a common dropdown or popover pattern where outside interaction closes the panel.

Dismissable UI

Outside interaction closes the panel

Closed

Open the panel, then click or focus anywhere outside it. This is the common dropdown and popover dismissal pattern.

The panel is closed.

Import

import { useClickOutside } from "react-rsc-kit/client";

Signature

const ref = useClickOutside<T>(handler, options?);

Parameters

NameTypeDefaultDescription
handler(event: Event) => voidrequiredRuns when an outside interaction is detected.
options.refRefObject<T | null>internal refOptional external ref for the primary target.
options.refsRefObject<Element | null>[][]Additional refs that should also count as inside.
options.ignore(Element | RefObject<Element | null>)[][]Elements or refs that should be ignored even if they are outside the target.
options.events("pointerdown" | "mousedown" | "mouseup" | "touchstart" | "touchend" | "focusin" | "focusout")[]["pointerdown"]Events to observe.
options.capturebooleantrueWhether listeners are attached in the capture phase.
options.passivebooleanfalseWhether listeners are passive when supported.
options.disabledbooleanfalseDisables outside detection without unmounting.
options.documentDocument | nullglobal documentCustom document target for portals or iframes.

Returns

  • ref: attach this ref to the element you want to monitor.

Usage

"use client"; import { useState } from "react"; import { useClickOutside } from "react-rsc-kit/client"; export function Dropdown() { const [open, setOpen] = useState(false); const ref = useClickOutside<HTMLDivElement>(() => setOpen(false), { events: ["pointerdown", "focusin"], disabled: !open, }); return ( <div> <button type="button" onClick={() => setOpen((value) => !value)}> Toggle </button> {open ? ( <div ref={ref}> <p>Dropdown content</p> </div> ) : null} </div> ); }

Notes

  • This hook is client-only.
  • pointerdown is the default because it covers mouse, touch, and pen in one event.
  • Use refs when the trigger and the content should both count as inside.
  • Use ignore for special elements like nested overlays or portal anchors.
  • The legacy (handler, events, capture) signature still works.
Last updated on