Skip to content

hook outsideclick

Paulo Gomes da Cruz Junior edited this page Nov 19, 2025 · 1 revision

🖱️ useOutsideClick Hook

Overview

useOutsideClick is a custom React hook that detects clicks outside of a specified element and triggers a callback. It is useful for closing dropdowns, modals, tooltips, or any UI component that should dismiss when the user clicks elsewhere on the page.

The hook listens for click events on the document and checks whether the click target lies outside the referenced element. If so, the provided callback is executed.

🔍 Usage Example

import { useRef, useState } from 'react';
import { useOutsideClick } from '@/hooks/useOutsideClick';

const Dropdown = () => {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement | null>(null);

  useOutsideClick(ref, () => setOpen(false), open);

  return (
    <div ref={ref}>
      <button onClick={() => setOpen(!open)}>Toggle</button>
      {open && <div className="menu">Dropdown content</div>}
    </div>
  );
};

⚙️ Implementation Details

  • Element Reference: Accepts a RefObject pointing to the element you want to monitor.
  • Callback: A function that runs when a click occurs outside the referenced element.
  • Enabled Flag: Optional boolean (default true). Controls whether the hook is active.
  • Event Handling:
    • Attaches a click event listener to the document.
    • Uses setTimeout to defer listener registration, ensuring it doesn’t immediately trigger on the same render cycle.
    • Cleans up the listener on unmount or when dependencies change.

📦 Return Type

function useOutsideClick<T extends HTMLElement>(
  elementRef: RefObject<T | null>,
  callback: () => void,
  enabled?: boolean
): void;
  • elementRef: Reference to the target element.
  • callback: Function executed when a click outside occurs.
  • enabled: Optional flag to enable/disable the hook.
  • Returns: Nothing — side-effect only.

🧰 Common Use Cases

  • Closing dropdown menus when clicking outside.
  • Dismissing modals or dialogs.
  • Hiding tooltips or popovers.
  • Detecting clicks outside of custom UI components.

Clone this wiki locally