Top React Hooks — Keypresses and Intersection

Image for post
Image for post
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:

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:

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:

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:

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:

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.

Conclusion

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

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