Top React Hooks — Mouse, Keyboard, and States
--
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:
yarn add react-hanger
The usePrevious
hook lets us get the previous value from the useState
hook.
For instance, we can write:
import React from "react";
import { usePrevious } from "react-hanger";export default function App() {
const [count, setCount] = React.useState(0);
const prevCount = usePrevious(count);
return (
<>
<button onClick={() => setCount(count => count + 1)}>increment</button>
<p>
Now: {count}, before: {prevCount}
</p>
</>
);
}
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:
npm install react-hook-mighty-mouse
Then we can use it by writing:
import React from "react";
import useMightyMouse from "react-hook-mighty-mouse";export default function App() {
const { position } = useMightyMouse();
return (
<div>
x:{position.client.x} y:{position.client.y}
</div>
);
}
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.