EventIntermediateBrowser APIshooks/events/useEventListener.ts

useEventListener

Add any event listener with cleanup.

Import

TypeScript
import { useEventListener } from '@/hooks';

API

Signature

useEventListener(event, handler, target?, options?)

When to use

Use useEventListener instead of re-implementing the same pattern in multiple components.

SSR / Next.js

No-ops until document/window exist.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useEventListener
Editor
function EscapeLogger() {
  useEventListener('keydown', (e) => {
    if (e.key === 'Escape') console.log('escaped');
  });
  return null;
}
Preview

Implementation source

Full library source for useEventListener — copy into your project when you are not installing a package yet.

hooks/events/useEventListener.ts
import { useEffect } from 'react';
import { getTargetElement, type BasicTarget } from '../utility/getTargetElement';
import { isBrowser } from '../utility/isBrowser';
import { useLatest } from '../utility/useLatest';

type WindowEventMapKey = keyof WindowEventMap;
type DocumentEventMapKey = keyof DocumentEventMap;
type HTMLElementEventMapKey = keyof HTMLElementEventMap;

export type EventMap = WindowEventMap & DocumentEventMap & HTMLElementEventMap;

export interface UseEventListenerOptions extends AddEventListenerOptions {
  enabled?: boolean;
}

/**
 * Generic event listener hook with automatic cleanup.
 * SSR-safe: no-ops when not in a browser.
 */
export function useEventListener<K extends WindowEventMapKey>(
  eventName: K,
  handler: (event: WindowEventMap[K]) => void,
  target?: BasicTarget<Window | Document | Element | null>,
  options?: UseEventListenerOptions,
): void;
export function useEventListener<K extends DocumentEventMapKey>(
  eventName: K,
  handler: (event: DocumentEventMap[K]) => void,
  target?: BasicTarget<Window | Document | Element | null>,
  options?: UseEventListenerOptions,
): void;
export function useEventListener<K extends HTMLElementEventMapKey>(
  eventName: K,
  handler: (event: HTMLElementEventMap[K]) => void,
  target?: BasicTarget<Window | Document | Element | null>,
  options?: UseEventListenerOptions,
): void;
export function useEventListener(
  eventName: string,
  handler: (event: Event) => void,
  target?: BasicTarget<Window | Document | Element | null>,
  options: UseEventListenerOptions = {},
): void {
  const { enabled = true, ...listenerOptions } = options;
  const handlerRef = useLatest(handler);

  useEffect(() => {
    if (!isBrowser() || !enabled) return;

    const eventTarget: EventTarget =
      target === undefined
        ? window
        : ((getTargetElement(target as BasicTarget<Element>) as
            | Element
            | undefined) ?? window);

    if (!eventTarget?.addEventListener) return;

    const listener = (event: Event) => handlerRef.current(event);
    eventTarget.addEventListener(eventName, listener, listenerOptions);
    return () => {
      eventTarget.removeEventListener(eventName, listener, listenerOptions);
    };
  }, [
    eventName,
    target,
    enabled,
    handlerRef,
    listenerOptions.capture,
    listenerOptions.once,
    listenerOptions.passive,
  ]);
}

Copy-paste example

useEventListener.example.tsx
'use client';

import { useEventListener } from '@/hooks';

export function EscapeLogger() {
  useEventListener('keydown', (e) => {
    if (e.key === 'Escape') console.log('escaped');
  });
  return null;
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Pass all relevant refs to useClickOutside (trigger + panel). Prefer useLatest for handlers.
  • Source of truth: open hooks/events/useEventListener.ts for implementation details