Skip to content

useEventListener

Hook to simplify add and remove EventListener use. It's persist during rerendering and automatically remove eventlistener on unMount component lifecycle.

Demo

INFO

The component has:

  • A buttonRef ref variable linked to an button node element with text click to log.
  • A useEventListener invocation with these options: type="click", listener=(e:Event)=>console.log(e). So the eventListener is attached to window and the invocation result is used to initialize a variable remove that remove the eventListener.
  • A useEventListener invocation like that above but attached at button node by buttonRef with listenerOpts capture=true and that stops event propagation.
  • A button with text Remove that, if clicked, invokes the removeEventListener.

At every click on Demo area the eventListener attached on object window logs in console the event, while the eventListener attached on button logs when button is clicked. When button remove is clicked it removes the eventListener on window object. The button eventListener is removed during component unmount.

Loading demo…
Show source code
tsx
import { useRef } from "react";
import { useEventListener } from "../../../..";

const UseEventListener = () => {
	const buttonRef = useRef<HTMLButtonElement>(null);
	const remove = useEventListener({ type: "click", listener: (e: Event) => console.log(e) });
	useEventListener({
		type: "click", listener: (e: Event) => {
			e.stopPropagation();
	}, element: buttonRef, listenerOpts: {capture: true} });

	return (<>
		<button onClick={() => remove()}>Remove</button>
		<button ref={buttonRef} style={{marginLeft: 10}}>click to log</button>
	</>);
}

UseEventListener.displayName = "UseEventListener";

export { UseEventListener };

Types

UseEventListenerProps

  • @template T - The event type key (e.g. "click", "keydown"). Must be a key of DocumentEventMap, HTMLElementEventMap, WindowEventMap, or an arbitrary string for custom events.
  • @template E - The element type the listener is attached to.

Parameters accepted by all overloads of useEventListener.

PropertyTypeRequiredDescription
typeT \| T[]The event type or array of event types to listen for (e.g. "click" or ["mouseenter", "mouseleave"]). All types in the array share the same listener callback.
listener(evt: Event) => unknown \| Promise<unknown>The event handler invoked whenever one of the specified event types fires. May return a value or a Promise — the return value is ignored by the hook.
elementRefObject<E> \| E \| WindowThe target on which the listener is registered. Accepts a React RefObject&lt;E&gt;, a direct element reference, or Window. Defaults to window when omitted.
listenerOptsboolean \| AddEventListenerOptionsOptions forwarded to addEventListener as the third argument. Accepts either a boolean shorthand for capture or a full {@link AddEventListenerOptions} object. When omitted, the listener is registered with the browser defaults.
effectType"normal" \| "layout"Controls which React effect hook is used to register the event listener: - "normal" (default) — Uses useEffect, which runs asynchronously after the browser has painted. - "layout" — Uses useLayoutEffect, which runs synchronously after DOM mutations but before the browser paints. Prefer this when the listener needs to read or modify layout immediately.

UseEventListenerResult

Return value of useEventListener.

A stable cleanup function that manually removes all registered event listeners from the target element. Calling it is optional — the hook cleans up automatically on unmount — but useful to detach listeners earlier on demand.

ts
export type UseEventListenerResult = () => void;

Released under the MIT License.