Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@use-it/event-listener

Package Overview
Dependencies
Maintainers
1
Versions
12
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@use-it/event-listener

A custom React Hook that provides a useEventListener.

  • 1.0.0-beta.3
  • next
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
98K
decreased by-8.76%
Maintainers
1
Weekly downloads
 
Created
Source

@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.

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 [, 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.

ParameterDescription
eventNameThe event name (string). Here is a list of common events.
handlerA 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.

KeyDescription
elementAn optional element to listen on. Defaults to global (i.e. window)
captureA 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.
passiveA Boolean indicating that the handler will never call preventDefault().
onceA 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.

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!

Keywords

FAQs

Package last updated on 27 Nov 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc