Skip to content

useClickOutside

Ref that fires a handler on outside pointer down.

A React hook that returns a ref and calls your handler when a pointer down happens outside the referenced element. Useful for closing popovers, menus, and dropdowns.

Installation

pnpm dlx shadcn@latest add @frontal-labs/use-click-outside

Usage

Close on outside click

import { useClickOutside } from "@/hooks/use-click-outside";
import { useState } from "react";
 
function Menu() {
  const [open, setOpen] = useState(true);
  const ref = useClickOutside<HTMLDivElement>(() => setOpen(false));
 
  if (!open) return null;
  return <div ref={ref}>Menu content</div>;
}

Conditionally enabled

Pass false as the second argument to pause listening (for example, only listen while open):

const ref = useClickOutside<HTMLDivElement>(() => setOpen(false), open);

API

function useClickOutside<T extends HTMLElement>(
  handler: (event: MouseEvent | TouchEvent) => void,
  enabled?: boolean,
): RefObject<T | null>;

Parameters

Return value

Returns a RefObject to attach to the element that should stay open. Clicks inside it (including children) are ignored.