useEventListener

Hook for adding event listeners with automatic cleanup.

Import

import { useEventListener } from "amvasdev-ui";

Signature

useEventListener(eventName, handler, element?, options?): void

Parameters

NameTypeRequiredDescription
eventNamestringYesName of the event to listen to
handler(event: Event) => voidYesEvent handler function
elementRefObject<HTMLElement> | undefinedNoTarget element (defaults to window)
optionsAddEventListenerOptionsNoEvent listener options

Live Demo

Window Event Listener

Press any key to see it detected:

Last key pressed: None

Element Event Listener

Click the button to increment the counter:

Examples

Window Events

import { useEventListener } from "amvasdev-ui";

function MyComponent() {
  // Listen to window events
  useEventListener("keydown", (event) => {
    if (event.key === "Escape") {
      console.log("Escape key pressed");
    }
  });

  return <div>Press Escape key</div>;
}

Element Events

import { useEventListener } from "amvasdev-ui";
import { useRef } from "react";

function MyComponent() {
  const buttonRef = useRef(null);

  // Listen to element events
  useEventListener(
    "click",
    (event) => {
      console.log("Button clicked");
    },
    buttonRef
  );

  return <button ref={buttonRef}>Click me</button>;
}

With Options

import { useEventListener } from "amvasdev-ui";

function MyComponent() {
  useEventListener(
    "scroll",
    (event) => {
      console.log("Scrolled");
    },
    undefined,
    { passive: true }
  );

  return <div>Scroll the page</div>;
}

Notes

  • Automatically cleans up event listeners on component unmount
  • Supports all standard DOM events