typescriptbeginner
useClickAway Hook
Fires a callback when a click is detected outside the referenced element.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useEffect, useRef, RefObject } from 'react';
export function useClickAway<T extends HTMLElement>(
callback: (event: MouseEvent | TouchEvent) => void
): RefObject<T | null> {
const ref = useRef<T | null>(null);
const callbackRef = useRef(callback);
useEffect(() => {
callbackRef.current = callback;
}, [callback]);
useEffect(() => {
const handler = (event: MouseEvent | TouchEvent) => {
const el = ref.current;
if (el && !el.contains(event.target as Node)) {
callbackRef.current(event);
}
};
document.addEventListener('mousedown', handler);
document.addEventListener('touchstart', handler);
return () => {
document.removeEventListener('mousedown', handler);
document.removeEventListener('touchstart', handler);
};
}, []);
return ref;
}Use Cases
- Dropdown close on outside click
- Modal dismiss
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptbeginner
useClickOutside — Outside Click Detection
Detect clicks outside a referenced element to close dropdowns, modals, and popover menus.
Best for: Dropdown menus
#hooks#click-outside
typescriptbeginner
useHover Hook
Tracks whether an element is being hovered using mouse enter/leave events with a ref.
Best for: Tooltip triggers
#hooks#mouse
typescriptbeginner
useClipboard Hook (Advanced)
Clipboard hook with read, write, and auto-reset of the copied state after a timeout.
Best for: Copy-to-clipboard buttons
#hooks#clipboard
typescriptintermediate
useLongPress Hook
Detects long press gestures on touch and mouse devices with configurable threshold.
Best for: Context menus
#hooks#gesture