useEventListener

DOM/Events

A React hook that provides a declarative way to add event listeners to DOM elements or window, with proper cleanup and TypeScript support for all DOM events.

Demo

1. Keyboard Events

Press any key combination to see it captured by the event listener.
?

2. Mouse Events

Move your mouse over the box to track coordinates relative to the container.

3. Scroll Events

Scroll the page to see the scroll position and direction.
Scroll Position
0px
Direction
-

Installation

npm install @thibault.sh/hooks

Usage

import { useEventListener } from "@thibault.sh/hooks";

function KeyPressTracker() {
  const [keys, setKeys] = useState<string[]>([]);
  
  useEventListener("keydown", (event) => {
    setKeys(prev => [...prev, event.key].slice(-5));
  });

  return (
    <div>
      <h3>Last 5 keys pressed:</h3>
      <div>{keys.join(", ")}</div>
    </div>
  );
}

function ClickTracker() {
  const buttonRef = useRef<HTMLButtonElement>(null);
  const [clicks, setClicks] = useState(0);
  
  useEventListener(
    "click",
    () => setClicks(c => c + 1),
    buttonRef
  );

  return (
    <button ref={buttonRef}>
      Clicked {clicks} times
    </button>
  );
}

API Reference

Parameters

eventName

The name of the DOM event to listen for (e.g., "click", "keydown", "scroll"). TypeScript will ensure you can only pass valid event names.

Type: keyof EventMap

handler

The event handler function that will be called when the event occurs. The function receives the event object with the correct type based on the event name.

Type: (event: EventMap[K]) => void

element

Optional ref to the target DOM element. If not provided, the event listener will be added to the window object. Must be a React ref created with useRef.

Type: RefObject<HTMLElement> | null

options

Optional addEventListener options or boolean for useCapture. These are passed directly to the native addEventListener method.

Type: boolean | AddEventListenerOptions

Features

Type Safety

Full TypeScript support for event names and handler types, ensuring you can only add listeners for valid DOM events with correct handler signatures.

Automatic Cleanup

Event listeners are automatically removed when the component unmounts or when dependencies change, preventing memory leaks and stale handlers.

Flexible Target

Works with both window events and element-specific events using React refs, providing a consistent API for all event types.

Native Options Support

Supports all native addEventListener options like capture, passive, and once, giving you full control over event behavior.

Common Use Cases

Keyboard Shortcuts

Listen for keyboard events to implement hotkeys and keyboard shortcuts that work globally or within specific components.

Click Outside Detection

Combine with refs to detect clicks outside a specific element, useful for implementing dropdown menus and modal dialogs.

Scroll-based Features

Track scroll position to implement infinite scrolling, scroll-to-top buttons, or scroll-based animations and transitions.

Window Resize Handling

Listen for window resize events to create responsive layouts and update UI elements based on viewport dimensions.