Skip to main content

Variable: useEventListener

const useEventListener: UseEventListener

Defined in: use-event-listener.ts:83

Attaches an event listener to window, document, an element, or any other EventTarget, and removes it automatically on cleanup.

  • Target: defaults to window. Pass document, an element, a ref, or any EventTarget. A null target (for example a ref that is not yet attached) attaches nothing.
  • Handler: always the latest one is called, so passing an inline function never causes re-subscription.
  • Options: standard addEventListener options (capture, passive, once, signal). Changing them re-subscribes; inline option objects are fine.
  • SSR: does nothing when there is no DOM.

Refs are read when the effect runs, so a ref that is attached in the same commit works, but swapping ref.current later does not re-subscribe.

Param​

type

The event name. The handler's event type is inferred from it for window, document and elements.

Param​

handler

Called with the event whenever it fires.

Param​

target

Where to listen. Defaults to window.

Param​

options

Standard addEventListener options.

Example​

// window
useEventListener("resize", () => setWidth(window.innerWidth));

// document
useEventListener("keydown", (e) => e.key === "Escape" && close(), document);

// element via ref
const ref = useRef<HTMLDivElement>(null);
useEventListener("scroll", (e) => console.log(e.currentTarget), ref, {
passive: true,
});