A React hook that handles binding/unbinding event listeners in a smart way.
npm install @utilityjs/use-event-listenerA React hook that handles binding/unbinding event listeners in a smart way.




``bash`
npm i @utilityjs/use-event-listener | yarn add @utilityjs/use-event-listener
`ts
useEventListener({
target: document,
eventType: "click",
handler: event => console.log(event)
});
useEventListener({
target: window,
eventType: "click",
handler: event => console.log(event)
});
useEventListener({
target: document.getElementById("target"),
eventType: "click",
handler: event => console.log(event)
});
`
`ts
type UseEventListener = {
config: {
target: T | null;
eventType: K;
handler: DocumentEventListener
options?: Options;
},
shouldAttach?: boolean
): void;
config: {
target: T | null;
eventType: K;
handler: WindowEventListener
options?: Options;
},
shouldAttach?: boolean
): void;
config: {
target: React.RefObject
eventType: K;
handler: ElementEventListener
options?: Options;
},
shouldAttach?: boolean
): void;
};
declare const useEventListener: UseEventListener;
`
#### config
##### config.target
The target to which the listener will be attached.
##### config.eventType
A case-sensitive string representing the event type to listen for.
##### config.handler
See The event listener callback for details on the callback itself.
##### config.options
See The event listener callback for details on the third parameter.
#### shouldAttach
If set to false`, the listener won't be attached. (default = true)