Top React Hooks — Keypresses and Intersection

Photo by Tierra Mallorca 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-use

The react-use library is a big library with many handy hooks.

We can use the useIntersection hook to detect whether an element is obscured or fully in view.

To use it, we can write:

import React from "react";
import { useIntersection } from "react-use";
export default function App() {
const intersectionRef = React.useRef(null);
const intersection = useIntersection(intersectionRef, {
root: null,
rootMargin: "0px",
threshold: 1
});
return (
<>
{Array(50)
.fill()
.map((_, i) => (
<p>{i}</p>
))}
<div ref={intersectionRef}>
{intersection && intersection.intersectionRatio < 1
? "Obscured"
: "Fully in view"}
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. In varius
nisl quis nibh laoreet, vitae feugiat nisi maximus. Nullam vitae mi
magna. Fusce lorem lacus,
</p>
</div>
</>
);
}

We created a ref that we pass into the useIntersection hook and the element that we want to watch.

The hook takes a few options.

root is the root element.

rootMargin is the margin of the root.

threshold is the threshold to determine whether the intersection exists.

The useKey hook lets us run a handler when a keyboard key is pressed.

For instance, we can write:

import React from "react";
import { useKey } from "react-use";
export default function App() {
const [count, set] = React.useState(0);
const increment = () => set(count => count + 1);
useKey("ArrowDown", increment);
return <div>Press arrow down: {count}</div>;
}

We use the useKey hook with the string with the key name and the function to run when the key is pressed.

It’s also available as a render prop.

To use it, we write:

import React from "react";
import UseKey from "react-use/lib/comps/UseKey";
export default function App() {
const [count, set] = React.useState(0);
const increment = () => set(count => count + 1);
return (
<>
<UseKey filter="ArrowDown" fn={increment} />
<div>Press arrow down: {count}</div>
</>
);
}

We used the UseKey component with the filter and fn props.

filter has the key name.

fn has the function to run when the key is pressed.

We can also use the useKey hook with a predicate:

import React from "react";
import { useKey } from "react-use";
export default function App() {
const [count, set] = React.useState(0);
const increment = () => set(count => count + 1);
const predicate = event => event.key === "ArrowDown";
useKey(predicate, increment, { event: "keyup" });
return (
<>
<div>Press arrow down: {count}</div>
</>
);
}

We have the predicate function to check the key property with the string of the key name.

We pass that into the useKey hook with the object with the event name.

The useKeyPress hook lets us listen for key presses.

For instance, we can write:

import React from "react";
import { useKeyPress } from "react-use";
const keys = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"];
export default function App() {
const states = [];
for (const key of keys) states.push(useKeyPress(key)[0]);
return (
<div>
Try pressing numbers
<br />
{states.join(", ")}
</div>
);
}

We have the useKeyPress hook with the argument being the key name.

This will let us detect whether the given key is pressed.

It returns an array with the first entry being true if the key is pressed.

Photo by Yash Raut on Unsplash

Conclusion

The react-use package has hooks to detect key presses and detect intersections.

Web developer. Subscribe to my email list now at https://thewebdev.info/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