Languages
[Edit]
EN

React - useEvent() hook

7 points
Created by:
Lilly-Grace-Greig
571

In this short article, we would like to show how in React, create custom event listener hook that cleans up event automatically when component is removed.

Quick solution:

Where:

  • object argument indicates object for what we want to add event,
  • event argument indicates event name that we want to listen,
    e.g. click, mousedown, mouseup, keydown, keyup, etc.,
  • callback argument indicates function that is called when event occurs on the object.

 

Practical example

Edit

In the below example we monitor 3 cases:

  • when key is down,
  • when key is up,
  • and when window losts focus (blur event).

Source code:

 

Alternative titles

  1. React - reusable event listener hook
  2. React - useEventListener() hook
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join