wkkkis-hooks

use-click-outside (use-click-outside)

Detects clicks outside of a referenced element.

v0.1.0

Usage

import { use-click-outside } from "@/hooks"
1"use client"; 2 3import React, { useRef, useState } from "react"; 4 5import { Button } from "@/components/ui/button"; 6import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; 7 8import { useClickOutside } from "@/components/hooks/use-click-outside"; 9 10export function UseClickOutsideDemo() { 11 const cardRef = useRef<HTMLDivElement>(null); 12 const [clickedOutside, setClickedOutside] = useState(false); 13 14 useClickOutside(cardRef, () => { 15 setClickedOutside(true); 16 }); 17 18 return ( 19 <Card ref={cardRef} className="w-full max-w-sm relative"> 20 <CardHeader> 21 <CardTitle>useClickOutside</CardTitle> 22 </CardHeader> 23 <CardContent className="space-y-4"> 24 <p className="text-sm"> 25 Click outside of the card to trigger an action. 26 </p> 27 {clickedOutside ? ( 28 <div className="text-red-500 font-semibold mb-2"> 29 You clicked outside of the card! 30 </div> 31 ) : null} 32 <Button onClick={() => setClickedOutside(false)} variant="outline"> 33 Reset 34 </Button> 35 </CardContent> 36 </Card> 37 ); 38} 39

Install

npx wkkkis-hooks add use-click-outside

Options

NameTypeDefaultDescription
refRefObjectnullThe reference to the element to detect clicks outside of
onClickOutsidefunctionnullThe function to call when a click outside the element occurs

Event Types & Capturing

  • Listens for both mousedown and touchstart events to detect clicks and touches outside the referenced element.
  • Listeners are attached in the capturing phase (ensuring early detection before event bubbling).

Callback Reference

  • The callback is always up-to-date using a ref, so you can safely use inline or dynamic functions without worrying about stale closures or unnecessary re-attachments.

Behavior

  • The callback is only called if the event target is outside the referenced element.
  • If the ref is null or the event target is not a DOM node, the callback is not called.

Cleanup

  • Event listeners are automatically removed when the component unmounts.

Caveats & Best Practices

  • Works for clicks/touches outside the referenced element, including those in React portals.
  • Not suitable for server-side rendering (SSR) directly, as it uses document .
  • If you use multiple refs or dynamic elements, ensure the ref is stable and points to the correct element.
  • The hook does not distinguish between left, right, or middle mouse buttons.

Files in this hook

SourceDestination
files/use-click-outside.tssrc/hooks/use-click-outside.ts