react-use-event-listener
TypeScript icon, indicating that this package has built-in type declarations

1.1.1 • Public • Published

react-use-event-listener

A custom React Hook that provides a declarative useEventListener.

npm version All Contributors TypeScript Build Status

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 react-use-event-listener

or

$ yarn add react-use-event-listener

Usage

Here is a basic setup.

import useEventListener from 'react-use-event-listener'
 
const MyElement: React.FunctionComponent = () => {
  useEventListener('beforeinstallprompt', (e) => {
    e.preventDefault()
  }) // uses window
 
  return (
    <div></div>
  )
}
 
const CustomEvent: React.FunctionComponent = () => {
  const elementRef = useRef()
 
  useEventListener('customevent', (e) => {
    // do stuff
  }, ref, { capture: true }) // accepts a ref
 
  return (
    <ExoticForwardedRef ref={elementRef} />
  )
}

Parameters

Here are the parameters that you can use. (* = optional)

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.
element* An optional element to listen on. Defaults to globalThis (i.e., window).
options* Optional options as in addEventListener.

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;
};

Live demo

You can view/edit the sample code above on CodeSandbox.

Edit demo app on CodeSandbox

License

MIT Licensed

Contributors

Thanks goes to these wonderful people (emoji key):

Donavon West
Donavon West

🚇 ⚠️ 💡 🤔 🚧 👀 🔧 💻
Kevin Kipp
Kevin Kipp

💻
Justin Hall
Justin Hall

💻 📖

This project follows the all-contributors specification. Contributions of any kind welcome!

Package Sidebar

Install

npm i react-use-event-listener

Weekly Downloads

1,950

Version

1.1.1

License

MIT

Unpacked Size

12.3 kB

Total Files

8

Last publish

Collaborators

  • pocesar