@use-it/event-listener
A custom React Hook that provides a declarative addEventListener.
Note: Version 1.x has been completely rewritten in TypeScript. See Parameters below important breaking changes.
This hook was inspired by Dan Abramov's
blog post
"Making setInterval Declarative with React Hooks".
I needed a way to simplify the plumbing around adding and removing an event listener
in a custom hook.
That lead to a chain of tweets
between Dan and myself.
Installation
$ npm i @use-it/event-listener
or
$ yarn add @use-it/event-listener
Usage
Here is a basic setup.
useEventListener(eventName, handler [, options]);
Parameters
Here are the parameters that you can use. (* = optional).
Note: in version 1.0, element
is now a key in options
. This represents a breaking change that could effect your code. Be sure to test before updating to 1.x from version 0.x.
Parameter | Description |
---|
eventName | The event name (string). Here is a list of common events. |
handler | A function that will be called whenever eventName fires on element . New in version 1.x: this can also be an object implementing the EventListener interface. |
options * | An optional Options object (see below). |
Options
Here is the Options object. All keys are optional.
See MDN for details on capture
, passive
, and once
.
Key | Description |
---|
element | An optional element to listen on. Defaults to global (i.e. window ) |
capture | A Boolean indicating that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree. |
passive | A Boolean indicating that the handler will never call preventDefault() . |
once | A Boolean indicating that the handler should be invoked at most once after being added. If true, the handler would be automatically removed when invoked. |
Return
This hook returns nothing.
Example
Let's look at some sample code. Suppose you would like to track the mouse
position. You could subscribe to mouse move events with like this.
const useMouseMove = () => {
const [coords, setCoords] = useState([0, 0]);
useEffect(() => {
const handler = ({ clientX, clientY }) => {
setCoords([clientX, clientY]);
};
window.addEventListener('mousemove', handler);
return () => {
window.removeEventListener('mousemove', handler);
};
}, []);
return coords;
};
Here we're using useEffect
to roll our own handler add/remove event listener.
useEventListener
abstracts this away. You only need to care about the event name
and the handler function.
const useMouseMove = () => {
const [coords, setCoords] = useState([0, 0]);
useEventListener('mousemove', ({ clientX, clientY }) => {
setCoords([clientX, clientY]);
});
return coords;
};
In TypeScript you can specify the type of the Event
to be more specific. Here we set the handler's event type to MouseEvent
.
const useMouseMove = () => {
const [coords, setCoords] = React.useState([0, 0]);
useEventListener('mousemove', ({ clientX, clientY }: MouseEvent) => {
setCoords([clientX, clientY]);
});
return coords;
};
Live demo
You can view/edit the sample code above on CodeSandbox.
License
MIT Licensed
Contributors
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!