Giter Site home page Giter Site logo

use-event-listener's Introduction

@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, options);

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).
options* An object { capture?: boolean, passive?: boolean, once?: boolean } to be passed to addEventListener. For advanced use cases. See MDN for details.

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

๐Ÿš‡ โš ๏ธ ๐Ÿ’ก ๐Ÿค” ๐Ÿšง ๐Ÿ‘€ ๐Ÿ”ง ๐Ÿ’ป

Kevin Kipp

๐Ÿ’ป

Justin Hall

๐Ÿ’ป ๐Ÿ“–

Jeow Li Huan

๐Ÿ‘€

Norman Rzepka

๐Ÿค”

Beer van der Drift

โš ๏ธ ๐Ÿ’ป

clingsoft

๐Ÿ’ป

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.