-
Notifications
You must be signed in to change notification settings - Fork 0
hook outsideclick
Paulo Gomes da Cruz Junior edited this page Nov 19, 2025
·
1 revision
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.
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>
);
};-
Element Reference: Accepts a
RefObjectpointing 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
clickevent listener to the document. - Uses
setTimeoutto defer listener registration, ensuring it doesn’t immediately trigger on the same render cycle. - Cleans up the listener on unmount or when dependencies change.
- Attaches a
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.
- Closing dropdown menus when clicking outside.
- Dismissing modals or dialogs.
- Hiding tooltips or popovers.
- Detecting clicks outside of custom UI components.