Skip to content
A custom React Hook that provides a declarative useEventListener
Branch: develop
Clone or download
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
__tests__ example is readme + more tests Feb 11, 2019
src initial commit Feb 11, 2019
types
.all-contributorsrc
.babelrc
.editorconfig
.eslintrc initial commit Feb 11, 2019
.gitignore initial commit Feb 11, 2019
.npmignore initial commit Feb 11, 2019
.prettierrc
.travis.yml make travis use node 10 vs. stable Apr 12, 2019
LICENSE
README.md docs: add wKovacs64 as a contributor (#6) Mar 5, 2019
package-lock.json
package.json

README.md

@use-it/event-listener

A custom React Hook that provides a declarative useEventListener.

npm version All Contributors

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, element);

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 global (i.e., window).

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!

You can’t perform that action at this time.