useOutsideClick
Detects clicks and touches outside a referenced element and calls a callback.
Signature
function useOutsideClick(callback: () => void): React.RefObject<HTMLDivElement>;
| Parameter | Type | Description |
|---|---|---|
callback |
() => void |
Called when a click/touch occurs outside the ref |
Returns a ref to attach to the element you want to monitor.
Usage
function Dropdown({ onClose }: { onClose: () => void }) {
const ref = useOutsideClick(onClose);
return (
<div ref={ref}>
<p>Dropdown content</p>
</div>
);
}
Notes
- Listens to both
mouseupandtouchendto cover desktop and mobile. - If
callbackchanges on every render, wrap it inuseCallbackto avoid resetting listeners unnecessarily. - Client-only (
'use client').