useEventListener

Events

A React hook that adds an event listener to a target element with automatic cleanup, supporting all standard DOM events on window, document, or specific HTML elements.

Installation

npm install @thibault.sh/hooks

API Reference

Signature

function useEventListener<K extends keyof EventMap>(
  eventName: K,
  handler: (event: EventMap[K]) => void,
  element?: RefObject<HTMLElement> | null,
  options?: boolean | AddEventListenerOptions
): void

Parameters

NameTypeDescriptionDefault
eventName
K
The name of the event to listen for (e.g., 'click', 'keydown', 'resize').-
handler
(event: EventMap[K]) => void
The event handler function that will be called when the event fires.-
element
optional
RefObject<HTMLElement> | null
Optional ref to the target element. Defaults to window if not provided.-
options
optional
boolean | AddEventListenerOptions
Optional event listener options (capture, once, passive, etc.).-

Returns

void

This hook does not return anything.

useEventListener Hook - React Event Listener Management