Overview
Creates a ref callback that attaches a DOM event listener to the current element node and cleans it up automatically. When the ref target changes, the previous listener is removed from the old node before attaching to the new node.Function Signature
Parameters
Name of the DOM event to listen for (e.g.,
"click", "mousedown", "keypress").Event handler invoked when the event fires on the attached element.
Optional native
addEventListener options such as capture, once, or passive.Return Value
A ref callback function to attach to your React element. The listener will be registered on the element and automatically cleaned up when the element is removed or the ref changes.
Usage Example
Features
- Automatic cleanup when component unmounts
- Removes listener from old element when ref target changes
- Type-safe event types based on HTML element event map
- Supports all native
addEventListeneroptions