Socket
Socket
Sign inDemoInstall

@use-it/event-listener

Package Overview
Dependencies
3
Maintainers
1
Versions
12
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    @use-it/event-listener

A custom React Hook that provides a useEventListener.


Version published
Weekly downloads
88K
increased by4.45%
Maintainers
1
Install size
15.2 kB
Created
Weekly downloads
 

Readme

Source

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

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

Keywords

FAQs

Last updated on 15 Nov 2021

Did you know?

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

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc