Size
0.44 kb
useEventListener
React version of `addEventListener`, optimized for performance and memory usage.
Installation
Usage
Attach an event listener to the target.
Target a DOM Element
You can use useEventListener
to attach event listeners to specific DOM elements.
Using a ref:
Using a stateful element:
Using querySelector:
Target the window / document
For single-page applications (SPAs), you can directly use the window
or document
object:
With SSR, you need to check if the code runs on the server before accessing the window object:
Trigger the listener manually
This example shows how to listen for the 'mousemove'
& 'mouseup'
global events only after the 'mousedown'
event has occurred.
API Reference
Parameters
The useEventListener
hook accepts four arguments:
Argument | Description |
---|---|
(1) | The element to attach the listener to. |
(2) | See MDN Docs |
(3) | See MDN Docs |
(4) | 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
Prop | Type | Default |
---|---|---|
remove | () => void | - |
add | () => void | - |