useEventListener()
The
useEventListener() hook simplifies adding event listeners to the window, document, or DOM elements. It handles binding and unbinding automatically, ensuring no memory leaks occur when components unmount.Import
typescript
Usage
Press any key on your keyboard
...
This demo listens to the keydown event on the global window object.
Component.tsx
API
Arguments
eventName– string The name of the event to listen for (e.g., ‘click‘, ‘keydown‘, ‘resize‘).handler– (event) => void The callback function to execute when the event fires.element– RefObject | HTMLElement | Window | Document (Optional) The target element to attach the listener to. Defaults towindowif not provided.options– boolean | AddEventListenerOptions (Optional) Options object to pass to the underlyingaddEventListener.