Categories
React Hooks

Top React Hooks — Keyboard and Query Strings

Spread the love

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:

import React from "react";
import useKeyboardJs from "react-use/lib/useKeyboardJs";

export default function App() {
  const [isPressed] = useKeyboardJs("a + b");

  return <div>[a + b] pressed: {isPressed ? "Yes" : "No"}</div>;
}

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:

import React from "react";
import { useKeyPressEvent } from "react-use";

export default function App() {
  const [count, setCount] = React.useState(0);

  const increment = () => setCount(count => count + 1);
  const decrement = () => setCount(count => count - 1);
  const reset = () => setCount(count => 0);

  useKeyPressEvent("[", increment, increment);
  useKeyPressEvent("]", decrement, decrement);
  useKeyPressEvent("r", reset);

  return (
    <div>
      <p>Count: {count}</p>
    </div>
  );
}

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:

import React from "react";
import { useLocation } from "react-use";

export default function App() {
  const state = useLocation();

  return <pre>{JSON.stringify(state, null, 2)}</pre>;
}

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:

import React from "react";
import { useSearchParam } from "react-use";

export default function App() {
  const foo = useSearchParam("foo");

  return (
    <>
      <div>
        <button
          onClick={() =>
            history.pushState({}, "", `${location.pathname}?foo=123`)
          }
        >
          123
        </button>
        <button
          onClick={() =>
            history.pushState({}, "", `${location.pathname}?foo=456`)
          }
        >
          456
        </button>
        <button
          onClick={() =>
            history.pushState({}, "", `${location.pathname}?foo=789`)
          }
        >
          789
        </button>
        <p>{foo}</p>
      </div>
    </>
  );
}

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *