Rehooks
Content

useEventListener

A custom hook to add and clean up an event listener on any target element.

useEventListener

Usage

Component.tsx
import { useEventListener } from "~/hooks/useEventListener";
 
function Component() {
  const divRef = useRef<HTMLDivElement>(null);
 
  useEventListener("click", () => {
    console.log("Clicked on window");
  });
 
  useEventListener(
    "mouseenter",
    () => {
      console.log("Mouse entered the div!");
    },
    divRef,
  );
 
  return (
    <div>
      <div ref={divRef}>Hover over this div</div>
    </div>
  );
}

API

useEventListener

function useEventListener<K extends keyof WindowEventMap>(
  eventName: K,
  handler: (event: WindowEventMap[K]) => void,
  element?: RefObject<HTMLElement> | Window,
): void;

Adds an event listener to the target element.

Parameters

NameTypeDescription
eventNameKThe event type (e.g. 'click', 'scroll', 'resize', etc.).
handler(event: WindowEventMap[K]) => voidThe event handler function.
elementRefObject<HTMLElement> | WindowThe target element to attach the event listener to. Default is window.

Returns

NameTypeDescription
undefinedvoid

On this page