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
| Param | Type | Description |
|---|---|---|
eventName | string | Event to subscribe to. Typed against the target. |
handler | (event: TEvent) => void | The listener. Always the latest reference. |
target | Window | Document | HTMLElement | RefObject | null | Where to attach. Defaults to window. null is tolerated. |
options | boolean | AddEventListenerOptions | Passed straight to addEventListener. |
Last updated on