useEventListener

Also exported as useEventListner (typo-tolerant alias) for the same function.

useEventListener keeps a ref to the latest handler so you can avoid stale closures without listing the handler in the effect dependency array. Pass target undefined to listen on window, null to register nothing, a raw EventTarget, or a RefObject (listeners attach to ref.current when it exists).

Import

import { useEventListener } from "h2o-library/hooks";
// or the alias
import { useEventListner } from "h2o-library/hooks";

Usage

Listen on window (default):

import { useEventListener } from "h2o-library/hooks";

useEventListener("keydown", (e) => {
  if (e.key === "Escape") closeAll();
});

Listen on a specific element via ref:

const ref = useRef<HTMLDivElement>(null);

useEventListener("scroll", (e) => console.log("scrolled", e.target), ref);

return (
  <div ref={ref} className="overflow-auto h-64">
    {/* … */}
  </div>
);

Pause registration by passing null as the target:

useEventListener("resize", onResize, paused ? null : undefined);

Example

Clicks on the blue area (only): 0

API

PropTypeDefaultDescription
eventstringEvent name (e.g. click, resize).
handler(ev: Event) => voidListener; always the latest on each call.
targetRefObject | EventTarget | null | undefinedwindowEvent target. undefined = window; null = skip.
optionsboolean | AddEventListenerOptionsundefinedNative listener options (e.g. { passive: true }).