What is @use-it/event-listener?
@use-it/event-listener is a React hook for adding and cleaning up event listeners in a declarative way. It simplifies the process of attaching event listeners to DOM elements or the window object, ensuring that they are properly cleaned up when the component unmounts.
What are @use-it/event-listener's main functionalities?
Window Event Listener
This feature allows you to add an event listener to the window object. In this example, a 'resize' event listener is added to the window, and the handleResize function is called whenever the window is resized.
import { useEffect } from 'react';
import useEventListener from '@use-it/event-listener';
function WindowResizeComponent() {
const handleResize = () => {
console.log('Window resized');
};
useEventListener('resize', handleResize, window);
return <div>Resize the window and check the console</div>;
}
Element Event Listener
This feature allows you to add an event listener to a specific DOM element. In this example, a 'click' event listener is added to a button element, and the handleClick function is called whenever the button is clicked.
import { useRef } from 'react';
import useEventListener from '@use-it/event-listener';
function ClickableComponent() {
const buttonRef = useRef(null);
const handleClick = () => {
console.log('Button clicked');
};
useEventListener('click', handleClick, buttonRef.current);
return <button ref={buttonRef}>Click me</button>;
}
Custom Event Listener
This feature allows you to add a custom event listener. In this example, a 'customEvent' listener is added to the window, and the handleCustomEvent function is called whenever the custom event is dispatched.
import { useEffect } from 'react';
import useEventListener from '@use-it/event-listener';
function CustomEventComponent() {
const handleCustomEvent = (event) => {
console.log('Custom event triggered', event.detail);
};
useEventListener('customEvent', handleCustomEvent, window);
useEffect(() => {
const event = new CustomEvent('customEvent', { detail: 'Hello, world!' });
window.dispatchEvent(event);
}, []);
return <div>Check the console for custom event details</div>;
}
Other packages similar to @use-it/event-listener
react-use
react-use is a collection of essential React hooks, including hooks for event listeners. It provides a useEvent hook that offers similar functionality to @use-it/event-listener, allowing you to add and clean up event listeners in a declarative way.
use-typed-event-listener
use-typed-event-listener is a React hook for adding event listeners with TypeScript support. It provides type-safe event listeners, ensuring that the event handler functions receive the correct event types. This package is useful if you are working with TypeScript and need type safety for your event listeners.
react-event-listener
react-event-listener is a package that provides a React component for managing event listeners. It allows you to add event listeners to the window, document, or any other DOM element declaratively using JSX. This package is useful if you prefer using components over hooks for managing event listeners.
@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!