Skip to main content

Function: useEventListener()

Call Signature​

function useEventListener<K>(
target,
event,
handler,
options?
): VoidFunction;

Defined in: react/src/hooks/useEventListener.ts:42

Listen to an event on a target for as long as the component is mounted.

The handler is read on every event, and the target and the options are compared by what they resolve to, so all three can be written inline. The listener is re-attached only when the element, the event or one of the options actually changes.

Type Parameters​

Type Parameter
K extends keyof DocumentEventMap

Parameters​

ParameterType
targetUseEventListenerTarget
eventK
handler(event) => void
options?UseEventListenerOptions

Returns​

VoidFunction

a function that removes the listener. It stays removed until the target, the event or the options change.

Call Signature​

function useEventListener<K>(
target,
event,
handler,
options?
): VoidFunction;

Defined in: react/src/hooks/useEventListener.ts:48

Listen to an event on a target for as long as the component is mounted.

The handler is read on every event, and the target and the options are compared by what they resolve to, so all three can be written inline. The listener is re-attached only when the element, the event or one of the options actually changes.

Type Parameters​

Type Parameter
K extends keyof WindowEventMap

Parameters​

ParameterType
targetUseEventListenerTarget
eventK
handler(event) => void
options?UseEventListenerOptions

Returns​

VoidFunction

a function that removes the listener. It stays removed until the target, the event or the options change.

Call Signature​

function useEventListener<K>(
target,
event,
handler,
options?
): VoidFunction;

Defined in: react/src/hooks/useEventListener.ts:54

Listen to an event on a target for as long as the component is mounted.

The handler is read on every event, and the target and the options are compared by what they resolve to, so all three can be written inline. The listener is re-attached only when the element, the event or one of the options actually changes.

Type Parameters​

Type Parameter
K extends keyof GlobalEventHandlersEventMap

Parameters​

ParameterType
targetUseEventListenerTarget
eventK
handler(event) => void
options?UseEventListenerOptions

Returns​

VoidFunction

a function that removes the listener. It stays removed until the target, the event or the options change.