useEventListener
useEventListener is a custom React hook that attaches an event listener to window, document, or a referenced element and always invokes the latest callback.
Usage
import { useRef, useState } from "react";
import { useEventListener } from "hookify-react";
export default function UseEventListenerExample() {
const buttonRef = useRef<HTMLButtonElement>(null);
const [message, setMessage] = useState("Click the button to see magic!");
useEventListener(
"click",
() => setMessage("Button clicked! Event listener is working 🎉"),
buttonRef,
);
useEventListener("keydown", (event) => {
if (event.key === "Enter") {
setMessage("You pressed the Enter key ⌨️");
}
});
return (
<div>
<p>{message}</p>
<button ref={buttonRef}>Click Me</button>
<p>Try pressing "Enter" on your keyboard!</p>
</div>
);
}
API Reference
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
eventType | string (a key of WindowEventMap / DocumentEventMap / HTMLElementEventMap) | - | The type of event to listen for (e.g. "click", "keydown"). |
callback | (event: Event) => void | - | The function to execute when the event fires. The latest callback is always used. |
elementRef | React.RefObject<Window | Document | HTMLElement | null> (optional) | window | A ref pointing to the target element. Defaults to window when omitted. |
options | boolean | AddEventListenerOptions (optional) | - | Additional options passed to addEventListener. |
Typed overloads are provided for
Window,Document, andHTMLElementtargets, so theeventargument is inferred correctly for each.
Return Value
This hook does not return a value.
Behavior
- Defaults the target to
windowwhen noelementRefis provided. - Always invokes the latest
callbackwithout re-subscribing, so the callback does not need to be memoized. - Captures
optionsin a ref so an inline options object does not force the subscription to re-run on every render. - Cleans up the listener automatically on unmount or when the target changes.
SSR Safety
useEventListener is safe during server-side rendering. It only touches the DOM inside an effect and bails out when there is no valid target with addEventListener.