Skip to Content
⭐️ Leave a star →
HooksuseEventListener

useEventListener

A typed addEventListener wrapper. Overloaded for Window, Document, and HTMLElement so the event name auto-completes and the event object is typed for you. Defaults to window. The listener is removed automatically on cleanup; null targets are tolerated so you can bind conditionally on refs that may not be ready yet.

The handler reference is read live — you can pass an inline arrow without re-subscribing on every render.

Used internally by ContextMenu, Group, and other components for global listener handling.

import { useEventListener } from '@wire-ui/react' function ResizeLogger() { useEventListener('resize', () => { console.log(window.innerWidth) }) return null }

Binding to a ref

Pass a ref/accessor as the third argument. The listener attaches when the target becomes available and detaches when it goes away.

import { useRef } from 'react' import { useEventListener } from '@wire-ui/react' function Outside() { const ref = useRef<HTMLDivElement>(null) useEventListener('click', (e) => console.log('clicked', e.target), ref) return <div ref={ref}>Click me</div> }

Parameters

ParamTypeDescription
eventNamestringEvent to subscribe to. Typed against the target.
handler(event: TEvent) => voidThe listener. Always the latest reference.
targetWindow | Document | HTMLElement | RefObject | nullWhere to attach. Defaults to window. null is tolerated.
optionsboolean | AddEventListenerOptionsPassed straight to addEventListener.
Last updated on

MIT License © 2026 wire-ui

useEventListener – Wire UI