useClickOutside — Outside Click Detection
Detect clicks outside a referenced element to close dropdowns, modals, and popover menus.
import { useEffect, useRef, RefObject } from 'react';
export function useClickOutside<T extends HTMLElement>(
handler: () => void
): RefObject<T | null> {
const ref = useRef<T | null>(null);
useEffect(() => {
const listener = (event: MouseEvent | TouchEvent) => {
const el = ref.current;
if (!el || el.contains(event.target as Node)) return;
handler();
};
document.addEventListener('mousedown', listener);
document.addEventListener('touchstart', listener);
return () => {
document.removeEventListener('mousedown', listener);
document.removeEventListener('touchstart', listener);
};
}, [handler]);
return ref;
}
// Usage:
// const ref = useClickOutside<HTMLDivElement>(() => setOpen(false));
// <div ref={ref}>{open && <Dropdown />}</div>Use Cases
- Dropdown menus
- Modal close behavior
- Tooltip dismissal
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
useFetch — Generic Data Fetching Hook
Custom React hook for data fetching with loading, error, and refetch states using the Fetch API.
useDebounce — Debounced Value Hook
Debounce any rapidly-changing value with a configurable delay. Useful for search inputs and resize handlers.
useLocalStorage — Persistent State Hook
Sync React state with localStorage including SSR safety, JSON serialization, and cross-tab updates.
useMediaQuery — Responsive Breakpoint Hook
Subscribe to CSS media query changes and get a boolean flag for responsive rendering logic in React.