Top React Hooks — Mouse, Keyboard, and States

Image for post
Image for post
Photo by Ryan Stone on Unsplash

Hooks contains our logic code in our React app.

We can create our own hooks and use hooks provided by other people.

In this article, we’ll look at some useful React hooks.

react-hanger

The react-hanger library comes with various hooks we can use to do various things.

To install it, we run:

The usePrevious hook lets us get the previous value from the useState hook.

For instance, we can write:

Then we have the count state with the setCount function returned from useState .

Then we pass the count state into the usePrevious hook to get the previous value of the count state returned.

React Mighty Mouse

React Mighty Mouse is a library with a hook that lets us track the mouse position.

To install it, we can run:

Then we can use it by writing:

We use the useMightyMouse hook to get an object with the position property.

Then we can get the mouse position as we move it with the client.x and client.y properties to get the x and y coordinates respectively.

react-hook-mousetrap

The react-hook-mousetrap library lets us watch for presses of a keyboard key combination.

We install it by running:

Then we can use it by writing:

We use the useMousetrap hook with the first argument being the key combination we want to track.

And the 2nd argument is the callback to run when the key combination is pressed.

React hookedUp

React hookedUp is a library with many hooks to make our lives easier.

To install it, we run:

or:

Then we can start using various hooks that it comes with.

It comes with the useArray hook to let us manipulate arrays easily.

For instance, we can write:

We have the useArray hook with the initial array as the value.

Then it returns the add , clear , and removeIndex methods to let us manipulate the array.

value has the current value.

add lets us append an entry.

clear clears the array.

removeIndex removes an item by its index.

Image for post
Image for post
Photo by Ricky Kharawala on Unsplash

Conclusion

The react-hanger and React hookedUp libraries comes with many hooks to help us manage states.

React Mighty Mouse and react-hook-mousetrap lets us watch for mouse position changes and key combo presses respectively.

Written by

Web developer. Subscribe to my email list now at http://jauyeung.net/subscribe/. Email me at hohanga@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store