HooksuseEventListener

useEventListener()

The useEventListener() hook simplifies adding event listeners to the window, document, or DOM elements. It handles binding and unbinding automatically, ensuring no memory leaks occur when components unmount.

Import

typescript
import { useEventListener } from 'the-react-hooks';

Usage

Press any key on your keyboard
...

This demo listens to the keydown event on the global window object.

Component.tsx
import { useEventListener } from 'the-react-hooks';
import { useState } from 'react';

export const Component = () => {
  const [key, setKey] = useState('');

  useEventListener('keydown', (event) => {
    setKey(event.key);
  });

  return (
    <div>
      <p>Press any key: {key}</p>
    </div>
  );
}

API

Arguments

  • eventName string The name of the event to listen for (e.g., ‘click‘, ‘keydown‘, ‘resize‘).
  • handler (event) => void The callback function to execute when the event fires.
  • element RefObject | HTMLElement | Window | Document (Optional) The target element to attach the listener to. Defaults to window if not provided.
  • options boolean | AddEventListenerOptions (Optional) Options object to pass to the underlying addEventListener.