one-hook
Size
0.44 kb
View source

useEventListener

React version of `addEventListener`, optimized for performance and memory usage.

Installation

npm install @1hook/use-event-listener

Usage

import {  } from '@1hook/use-event-listener'

Attach an event listener to the target.

(, 'click', () => .('click'))

Target a DOM Element

You can use useEventListener to attach event listeners to specific DOM elements.

Using a ref:

function () {
  const  = <HTMLDivElement | null>(null)

  (, 'scroll', () => .('scroll'))

  return < ={} />
}

Using a stateful element:

function () {
  const [, ] = <HTMLDivElement | null>(null)

  (, 'scroll', () => .('scroll'))

  return < ={} />
}

Using querySelector:

function () {
  const  = .('body > .scrollable')

  (, 'scroll', () => .('scroll'))

  return < />
}

Target the window / document

For single-page applications (SPAs), you can directly use the window or document object:

(, 'click', () => .(.))

With SSR, you need to check if the code runs on the server before accessing the window object:

import {  } from '@1hook/use-event-listener'

(! && , 'click', () => .(.))

Trigger the listener manually

This example shows how to listen for the 'mousemove' & 'mouseup' global events only after the 'mousedown' event has occurred.

(.('target'), 'mousedown', () => {
  // Activate mousemove and mouseup listeners after mousedown occurs
  .()
  .()
})

const  = (
  ,
  'mousemove',
  () => .('Mouse Move'),
  { : false }, // Do not attach the listener automatically
)

const  = (
  ,
  'mouseup',
  () => {
    // Remove both listeners after mouseup event
    .()
    .()
  },
  { : false }, // Do not attach the listener automatically
)

API Reference

Parameters

The useEventListener hook accepts four arguments:

ArgumentDescription
(1) target
The element to attach the listener to.
(2) type
See MDN Docs
(3) listener
See MDN Docs
(4) options
Event listener options (see MDN docs) with the following differences:
- autoListen: if false the listener is not attached automatically on mount.
- signal is omitted

UseEventListenerReturn

What `useEventListener` returns

PropTypeDefault
remove
() => void
-
add
() => void
-

On this page