Founding price: $35, then $99 after 23:59 UTC on 4 November, then $99
Get ProAttach a typed event listener to the window, the document or an element, always calling your newest handler and removing it on cleanup.
Derived from this item’s props table, because it declares no controls of its own. This item has no standalone playground, so changes update the code, the share link and the AI prompt.
Use it for any listener that is not a React prop: window resize, document keydown, a listener on an element held in a ref, or a passive wheel handler.
Do not use it for events on elements you render yourself; use the React prop (onClick) there.
import { useEventListener } from "@/hooks/use-event-listener"useEventListener("keydown", (event) => {
if (event.key === "Escape") close()
})
useEventListener("scroll", onScroll, { target: panelRef, passive: true })useEventListener(type, handler, options?): void
| Option | Type | Default | Description |
|---|---|---|---|
target | Window | Document | HTMLElement | RefObject | null | window | Where to listen. A ref is read when the effect runs. null disables the listener. |
capture | boolean | false | Capture phase. |
passive | boolean | - | Passive listener (set it for scroll and touch). |
once | boolean | false | Remove after the first call. |
The handler is stored in a ref, so changing it does not re-attach the listener. Types come from the event name and the target.
A hook has no markup. Global key handlers must not steal keys from inputs or from assistive technology; check event.target and avoid single-character shortcuts unless they can be turned off or remapped (WCAG 2.1.4).
The hook ships with renderHook tests (use-event-listener.test.ts) covering its behaviour, cleanup on unmount and server-safe defaults. It is safe to render on the server.