Top React Hooks — Keyboard and Query Strings

Image for post
Image for post
Photo by Aryan Dhiman 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.

The useKeyboardJs hook lets us detect key combo presses.

For instance, we can write:

We also need to install the keyboardjs package for this hook to work.

To use the hook, we just pass in the string.

And it returns an array with the first entry being the key combo that’s pressed.

Then when we press both keys a and b, we’ll show ‘Yes’.

The useKeyPressEvent hook fires both keydown and keyup callbacks.

But it only triggers each callback once per press cycle.

It’ll fire the keydown callback only once if we press and hold a key.

For instance, we can use it by writing:

We create the functions increment , decrement , and reset to change the count state.

The useKeyPressEvent hook lets us listen to key presses.

The first argument is the key.

The 2nd and 3rd arguments are the callbacks that run when the key is down and up.

The useLocation hook lets us track the browser’s location.

We need to install the Geolocation API polyfill for IE to support IE.

To use it, we write:

We have various properties like in the state like trigger , state m hash , host , hostname , etc.

hash hash the URL segment after the pound sign.

hostname has the hostname.

href has the whole URL.

origin has the root URL segment.

port has the port.

pathname has the pathname without the root part.

protocol has the protocol that we communicate through.

search has the query string.

The useSearchParam hook lets us track location search params.

For instance, we can use it by writing:

In each button, we called pushState to go to a URL with different query strings.

The useSearchParam hook takes the key of the query string to get the value of and returns the value.

Then we’ll see the return value rendered.

Conclusion

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

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