Repository navigation
hook outsideclick
Paulo Gomes da Cruz Junior edited this page Apr 13, 2026
·
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.
This wiki documents NR Waste Plus for users and developers. Verify security and deployment guidance against the current application configuration before applying it elsewhere.
- Report an issue or ask a question in the GitHub repository.
- Follow the Contributing Guidelines to propose an update.
- Read the Code of Conduct.
Collection indexes support human browsing and machine retrieval. Keep both current when adding or moving wiki pages.
NR Waste Plus Wiki | GitHub Repository