Skip to main content

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​

ParameterTypeDefaultDescription
eventTypestring (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.
elementRefReact.RefObject<Window | Document | HTMLElement | null> (optional)windowA ref pointing to the target element. Defaults to window when omitted.
optionsboolean | AddEventListenerOptions (optional)-Additional options passed to addEventListener.

Typed overloads are provided for Window, Document, and HTMLElement targets, so the event argument is inferred correctly for each.

Return Value​

This hook does not return a value.

Behavior​

  • Defaults the target to window when no elementRef is provided.
  • Always invokes the latest callback without re-subscribing, so the callback does not need to be memoized.
  • Captures options in 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.