useEventListener

Tags:

A React Hook that use EventListener with ease.

Register using addEventListener on mounted, and removeEventListener automatically on unmounted.

Demo

Double-click anywhere on the window, or click inside the dotted box below to see the Toast prompt.

Source

Click inside this dashed box to see the toast

Usage

See API for more details.

Source

Click links below to view source on GitHub.

API

// target is `window` by default useEventListener(eventName, handler, options) // specify tagret explicitly useEventListener(eventTarget, eventName, handler, options)

EventTarget

Target can be:

A "⚛️" prefix is means that it can also be a React Ref that contains it.

  • window (default)
  • document
  • ⚛️ native EventTarget
  • ⚛️ DOM Element
  • ⚛️ Object that implements EventTarget interface (addEventListener and removeEventListener)
  • ⚛️ null or undefined

EventName

string | string[], a string or strings representing the event types to listen for. It will be automatically inferred from the EventTarget type.

Handler

Function | Funtions[], a function or funcitons that receives a notification when an event of the specified type occurs. Event will also be automatically.

Options

Options that will be passed to addEventListener and removeEventListener.

export type Options = boolean | AddEventListenerOptions | undefined

For more details options, see EventTarget.addEventListener#options

Returns

A function that removes the event listener.