Typed HooksGetting StarteduseEventListener

useEventListener

A type-safe custom hook for managing DOM event listeners in React with support for event delegation.

useEventListener is a powerful and type-safe React hook that simplifies adding event listeners to DOM elements. It provides full TypeScript support with proper event typing based on the target element, supports event delegation through CSS selectors, and automatically handles cleanup to prevent memory leaks.

The hook works with various DOM elements including Window, Document, HTMLElement, and SVGElement, ensuring type safety by constraining event names to valid events for each element type. It also supports all standard addEventListener options and includes event delegation for handling events on dynamically created child elements.

Status
Visible
Click anywhere to toggle visibility (click count: 0)
useEventListener('click', handler) - Attaches to window by default

Installation

pnpm dlx shadcn@latest add https://shaddy-docs.vercel.app/r/use-event-listener

API

useEventListener<T, K>(eventName, handler, element?, options?): void

Parameters

ParameterTypeDescription
eventNameK extends EventNameType<T>The name of the event to listen for (e.g., 'click', 'resize', 'keydown')
handler(event: EventType<T, K>, delegateTarget?: Element) => voidThe callback function that handles the event with proper typing
elementT | null | undefinedThe target element to attach the listener to. Defaults to window if not provided
optionsUseEventListenerOptions | boolean | undefinedOptional addEventListener options or useCapture boolean. Includes selector for event delegation

Options

The options parameter extends standard AddEventListenerOptions with:

PropertyTypeDescription
selectorstring | undefinedCSS selector for event delegation. When provided, handler only fires when event target matches this selector
captureboolean | undefinedStandard addEventListener capture option
onceboolean | undefinedStandard addEventListener once option
passiveboolean | undefinedStandard addEventListener passive option
signalAbortSignal | undefinedStandard addEventListener signal option

Returns

  • void - This hook doesn't return anything, it manages the event listener lifecycle internally.