useEventListenerRef
Returns a callback ref that manages an event listener on its current HTML element.
About
useEventListenerRef combines a callback ref with an element event listener. Use it when the hook should own both discovering the DOM element and subscribing to one of its events.
Example
import { useState } from "react";
import { useEventListenerRef } from "rooks";
export default function ClickTracker() {
const [clicks, setClicks] = useState(0);
const buttonRef = useEventListenerRef("click", () => {
setClicks((current) => current + 1);
});
return (
<button type="button" ref={buttonRef}>
Recorded {clicks} clicks
</button>
);
}Parameters
eventName: string— required event type passed toaddEventListener.callback: (...args: unknown[]) => void— required listener. The attached listener calls the latest callback without resubscribing solely because the callback changed.listenerOptions?: AddEventListenerOptions | EventListenerOptions | boolean— add/remove options; defaults to{}.isLayoutEffect?: boolean— attaches in an isomorphic layout effect whentrue, otherwise a passive effect. It defaults tofalseand should remain constant for the component's lifetime.
Return value
Returns a stable callback ref (element: HTMLElement | null) => void. Pass it to one HTML element's ref prop.
Behavior and lifecycle
When React supplies an element, the hook attaches the listener after the selected effect runs. Moving the ref, changing the event/options, or unmounting removes the listener from the previous element with matching options. The callback is kept fresh through a ref, so state and props do not become stale.
Compatibility and accessibility
No DOM work occurs during SSR because the ref has no element and effects do not run. Prefer the element's native React event prop when no reusable listener abstraction is needed. The ref does not add keyboard behavior or semantics to a non-interactive element; use a button or implement the corresponding accessible interaction. See SSR and browser APIs.
Related
- useEventListener supports explicit DOM and browser event targets through the experimental entrypoint.
- useRefElement exposes both a callback ref and its current element.