useEventListener
Use EventListener with ease.
useEventListener attaches a DOM event listener to a target element (or window/document) and automatically removes it on unmount or when dependencies change. It accepts the event name, handler function, and an optional target ref or element. The handler is always up-to-date without needing to re-register the listener, thanks to an internal ref via useLatest.
When to Use
- Listening for keyboard shortcuts, mouse clicks, or scroll events on specific elements
- Attaching
resize,visibilitychange, orstorageevents towindow/document - Any case where you need automatic cleanup of event listeners tied to component lifecycle
Notes
- SSR-safe: Skips listener registration during server-side rendering since
window/documentare unavailable. - Stable handler: Uses
useLatestinternally so the handler always points to the latest closure without re-attaching the listener. - The third argument defaults to
windowand accepts a raw element, a ref object, or a function returning an element. See alsouseEventfor a stable callback ref pattern, anduseDebounceFn/useThrottleFnfor rate-limited event handling.
Usage
Live Editor
function Demo() { const buttonRef = useRef<HTMLButtonElement>(null); const [state, setState] = useState("NO DB Click"); const onDBClick = () => { setState("DB Clicked"); }; const onClick = (event: Event) => { console.log("button clicked!", event); }; const onVisibilityChange = (event: Event) => { console.log("doc visibility changed!", { isVisible: !document.hidden, event, }); }; // example with window based event useEventListener("dblclick", onDBClick); // example with document based event useEventListener("visibilitychange", onVisibilityChange, () => document); // example with element based event useEventListener("click", onClick, buttonRef); return ( <div> <p>{state}</p> <button ref={buttonRef}>Click me</button> </div> ); };
Result
API
useEventListener
Returns
void
Arguments
| Argument | Description | Type | DefaultValue |
|---|---|---|---|
| eventName | event name | string (Required) | - |
| handler | event handler | (event: any) => void (Required) | - |
| element | dom element | EventTarget | Element | Document | HTMLElement | Window | null | undefined | window |
| options | listener options | boolean | AddEventListenerOptions | undefined | - |