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
Click inside
API
| Prop | Type | Default | Description |
|---|---|---|---|
event | string | — | Event name (e.g. click, resize). |
handler | (ev: Event) => void | — | Listener; always the latest on each call. |
target | RefObject | EventTarget | null | undefined | window | Event target. undefined = window; null = skip. |
options | boolean | AddEventListenerOptions | undefined | Native listener options (e.g. { passive: true }). |