useEventListener
Declarative DOM event listener with cleanup.
Attaches a listener to window (default), document, an element or a ref, and removes it on unmount. The latest handler always runs without re-subscribing, and refs are re-read after every commit so the listener follows conditional elements.
Usage
Examples
Window events
Document events
An element through a ref
API
4 options
1 return value
Accessibility
Keyboard listeners on window or document must not swallow keys that belong to focused controls; check event.target and event.defaultPrevented.
Notes
- Mark scroll and touch listeners passive so they never delay scrolling.
Related
useCopyToClipboardCopy text with a temporary copied state and a fallback.useHotkeyKeyboard shortcuts with platform-aware mod keys.useHoverPointer hover state with props to spread, ignoring touch.useMousePositionTrack viewport, page and optional element-relative pointer coordinates.useOnClickOutsideRun a callback when a press lands outside one or more elements.useScrollLockLock page scrolling while a custom overlay is open.