useEventListener

Listen for events on a target element with useEventListener.

Install:

Note: This hook depends on React’s experimental useEffectEvent.

npm i @uidotdev/usehooks@experimental react@experimental react-dom@experimental

Description:

The useEventListener hook enables you to add event listeners to a target element within a React component. By using useEventListener, you can handle various types of events, such as mouse events or keyboard events, and specify the target element, event name, event handler function, and additional options. applications.

Parameters

NameTypeDescription
targetref or DOM elementThe target element to attach the event listener to. It can be either a ref object (ref.current) or a DOM element.
eventNamestringThe name of the event to listen for.
handlerfunctionThe event handler function to be executed when the event is triggered.
optionsobject(Optional) Additional options for the event listener.
options.capturebooleanSpecifies whether the event should be captured during the capturing phase. Default is false.
options.passivebooleanSpecifies whether the event listener will not call preventDefault(). Default is false.
options.oncebooleanSpecifies whether the event listener should only be invoked once. Default is false.

Demo:

Example:

More Hooks:

Sort: