Categories
React Hooks

Top React Hooks — Keyboard and Query Strings

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.

Categories
React Hooks

Top React Hooks — Idleness, Geolocation, and Hashes

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 useGeolocation hook lets us get the location data within our React app.

We can use it by writing:

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

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

  return <>{JSON.stringify(state)}</>;
}

We use the useGeolocation to get various pieces of data.

It includes the accuracy, latitude, longitude, altitude, speed, and loading state.

The useHover and useHoverDirty gooks lets us watch for hovering of an element.

To use the useHover hook, we can write:

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

export default function App() {
  const element = hovered => <div>Hover me {hovered.toString()}</div>;
  const [hoverable, hovered] = useHover(element);

  return (
    <div>
      {hoverable}
      <div>{hovered.toString()}</div>
    </div>
  );
}

We use the useHover hook with the element of our choice.

The element is a function that takes the hovered parameter and returns some elements.

useHover returns an array with the hoverable and hovered variables.

hoverable indicates whether an element is hoverable.

hovered indicates whether the element is hovered on.

useHover uses onMouseEnter and onMouseLeave to watch for hovering.

useHoverDirty accept a React ref.

And it sets its handlers to the onmouseover and onmouseout properties.

To use it, we write:

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

export default function App() {
  const ref = React.useRef();
  const isHovering = useHoverDirty(ref);

  return (
    <div ref={ref}>
      <div>{isHovering.toString()}</div>
    </div>
  );
}

useHoverDirty takes a ref, which we also pass to the element we want to watch hover on.

It returns the isHovering variable which indicates whether we’re hovering on it or not.

useHash is a hook that tracks the browser location’s hash.

To use it, we can write:

import React from "react";
import { useHash, useMount } from "react-use";

export default function App() {
  const [hash, setHash] = useHash();

  useMount(() => {
    setHash("#/foo/page?userId=123");
  });

  return (
    <div>
      <div>
        <pre>{window.location.href}</pre>
      </div>
      <div>Edit hash: </div>
      <div>
        <input
          style={{ width: "100%" }}
          value={hash}
          onChange={e => setHash(e.target.value)}
        />
      </div>
    </div>
  );
}

to use it.

We use the useMount hook which changes the hash when the component mounts.

We did that with the setHash function returned by the useHash hook.

hash has the hash value with the pound sign.

When we get the window.location.href , we’ll get the whole URL with the hash.

The useIdle hook let us determine if the page id idle.

To use it, we write:

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

export default function App() {
  const isIdle = useIdle(1000);

  return (
    <div>
      <div>User is idle: {isIdle ? "yes" : "no"}</div>
    </div>
  );
}

We use the useIdle hook with the time to idle in milliseconds in the argument.

It returns the isIdle boolean variable to indicate whether the page is idle or not.

Conclusion

The react-use package comes with many useful hooks like geolocation, watching hovering, and watching for idleness.

Categories
React Hooks

Top React Hooks —File Drop, Audio and Clicks

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 useAudio hook creates an audio element.

It tracks the state and exposes playback controls.

For instance, we can write:

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

export default function App() {
  const [audio, state, controls, ref] = useAudio({
    src: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3",
    autoPlay: true
  });

  return (
    <>
      {audio}
      <pre>{JSON.stringify(state, null, 2)}</pre>
      <button onClick={controls.pause}>Pause</button>
      <button onClick={controls.play}>Play</button>
      <button onClick={controls.mute}>Mute</button>
      <button onClick={controls.unmute}>Un-mute</button>
      <button onClick={() => controls.volume(0.1)}>Volume: 10%</button>
      <button onClick={() => controls.volume(0.5)}>Volume: 50%</button>
      <button onClick={() => controls.volume(1)}>Volume: 100%</button>
      <button onClick={() => controls.seek(state.time - 5)}>-5 sec</button>
      <button onClick={() => controls.seek(state.time + 5)}>+5 sec</button>
    </>
  );
}

to use the useAudio hook.

The argument is the object with the audio URL and autoPlay option.

controls has the methods to control the audio playback.

state has the audio playing state.

The state includes the time, duration, paused, muted, and volume.

The useClickAway hook lets us trigger a callback when the user clicks outside the target element.

For example, we can write:

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

export default function App() {
  const ref = React.useRef(null);
  useClickAway(ref, () => {
    console.log("clicked outside");
  });

  return (
    <div
      ref={ref}
      style={{
        width: 200,
        height: 200,
        background: "green"
      }}
    />
  );
}

to use the hook.

useClickAway takes a ref for the element to watch ad a callback that runs some code when we click outside that element.

We also pass in the ref to the element we want to watch the clicks outside so that we can watch for clicks outside.

The useCss hook lets us change CSS dynamically in our app.

To use it, we can write:

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

export default function App() {
  const className = useCss({
    color: "green",
    border: "1px solid green",
    "&:hover": {
      color: "blue"
    }
  });

  return <div className={className}>Hover me</div>;
}

Then useCss hook takes an object with some styles in it.

It returns the className which we can use to style our component.

We can use the useDrop hook to get the file that’s dropped into the container.

For instance, we can write:

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

export default function App() {
  const state = useDrop({
    onFiles: files => console.log("files", files),
    onUri: uri => console.log("uri", uri),
    onText: text => console.log("text", text)
  });

  return (
    <div style={{ width: 200, height: 200, background: "orange" }}>
      Drop file here
    </div>
  );
}

The useDrop hook takes an object with some properties.

onFiles has the files object as the parameter and we can do things with it.

files has the files that have been dropped into the element.

onUri runs when we drop a URL and onText runs when we drop some text in there.

Conclusion

The react-use package has hooks to let us create audio elements, listen to clicks outside, and listen to file drops.

Categories
React Hooks

Top React Hooks — Drop Area, Speech, Full Screen, and Slider

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.

useDropArea

The useDropArea hook lets us listen to file drops with elements.

For example, we can write:

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

export default function App() {
  const [bond, state] = useDropArea({
    onFiles: files => console.log("files", files),
    onUri: uri => console.log("uri", uri),
    onText: text => console.log("text", text)
  });

  return (
    <div {...bond} style={{ width: 200, height: 200, background: "orange" }}>
      Drop file here
    </div>
  );
}

We have the useDropArea hook that returns an object that we can use as props to make an element accept files being dropped into it.

The callbacks in the object are run when those items are dropped into it.

useFullscreen

To let us toggle full-screen mode, the useFullscreen hook lets us add full screen toggling capability to our app.

For instance, we can write:

import React from "react";
import { useFullscreen, useToggle } from "react-use";

export default function App() {
  const ref = React.useRef(null);
  const [show, toggle] = useToggle(false);
  const isFullscreen = useFullscreen(ref, show, {
    onClose: () => toggle(false)
  });

  return (
    <div ref={ref} style={{ backgroundColor: "white" }}>
      <div>{isFullscreen ? "Fullscreen" : "Not fullscreen"}</div>
      <button onClick={() => toggle()}>Toggle</button>
    </div>
  );
}

We have the useToggle hook to let us toggle full screen.

The useFullscreen hook takes a ref that we want to toggle fullscreen.

show is the state of the full-screen toggle.

toggle is a function to toggle show .

isFullScreen has the full-screen state.

useSlider

The useSlider state lets us add slider behavior to any HTML element.

It supports both mouse and touch events.

For example, we can write:

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

export default function App() {
  const ref = React.useRef(null);
  const { isSliding, value, pos, length } = useSlider(ref);

  return (
    <div>
      <div ref={ref} style={{ position: "relative" }}>
        <p style={{ textAlign: "center", color: isSliding ? "red" : "green" }}>
          {Math.round(value * 100)}%
        </p>
        <div style={{ position: "absolute", left: pos }}>slide here</div>
      </div>
    </div>
  );
}

We use the useSlider hook with a ref to let us create a slide.

We pass the ref into the ref prop.

It returns an object with a few properties.

isSliding is a boolean that’s true if we’re sliding the slider.

value has the value of the slider.

pos has the position.

length has the length of the slide relative to the left.

useSpeech

useSpeech lets our app speak any text we pass into it.

For instance, we can use it by writing:

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

const voices = window.speechSynthesis.getVoices();

export default function App() {
  const state = useSpeech("a quick brow box jump over the dog", {
    rate: 0.8,
    pitch: 0.5,
    voice: voices[0]
  });

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

To use it, we just pass in the text we want to speak as the first argument.

The 2nd argument has the voice settings.

It includes the speed, which is the rate , the pitch, and the voice to speak the text with.

It returns the state which tells us whether the text is being spoken, the rate, the pitch, and the language.

Conclusion

react-use lets us create a slider, a file drop area, toggle full screen, and speak text.

Categories
React Hooks

Top React Hooks — Debounce, Error, Favicon, and Local Storage

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.

useDebounce

The useDebounce hook lets us denounce our callbacks by our give number of milliseconds.

For instance, we can write:

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

export default function App() {
  const [val, setVal] = React.useState("");
  const [debouncedValue, setDebouncedValue] = React.useState("");

  const [, cancel] = useDebounce(
    () => {
      setDebouncedValue(val);
    },
    2000,
    [val]
    );

  return (
    <div>
      <input
        type="text"
        value={val}
        placeholder="Debounced input"
        onChange={({ currentTarget }) => {
          setVal(currentTarget.value);
        }}
      />
      <div>
        <p>Debounced value: {debouncedValue}</p>
        <button onClick={cancel}>Cancel debounce</button>
      </div>
    </div>
  );
}

We call the useDebounce hook with a callback to set the debounced value in the callback.

The 2nd argument is the number of milliseconds to debounce.

The 3rd is an array with the values to watch for and call the callback when they change.

It’ll be debounced by the delay in the 2nd argument.

The hook returns an array with the cancel function to cancel the debouncing.

useError

The useError hook lets us throw errors in our code.

It’ll be caught with the ErrorBoundary component is we wrap our component with it.

For instance, we can write:

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

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    console.log(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return <h1>error.</h1>;
    }

    return this.props.children;
  }
}

const Foo = () => {
  const dispatchError = useError();

  const clickHandler = () => {
    dispatchError(new Error("error!"));
  };

  return <button onClick={clickHandler}>Click me to throw</button>;
};

export default function App() {
  return (
    <ErrorBoundary>
      <Foo />
    </ErrorBoundary>
  );
}

We create the ErrorBoundary component with methods to log the error.

The getDerivedStateFromError function runs to return the state when an error occurs.

componenrDidCatch catches the error.

The Foo component uses the useError hook, which returns the dispatchError function that takes an Error instance.

This lets us throw an error and catch it with the ErrorBoundary component.

useFavicon

The useFavicon hook lets us set the favicon of the page.

For instance, we can write:

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

export default function App() {
  useFavicon("https://api.faviconkit.com/aws.amazon.com/144");

  return <div />;
}

We just call the useFavicon hook with the URL of the favicon change our app to that favicon.

useLocalStorage

To manage local storage, we can use the useLocalStorage hook.

It returns an array with the value, a function to set the value, and a function to remove the item.

The argument it takes is the key of the local storage item.

To use it, we can write:

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

export default function App() {
  const [value, setValue, remove] = useLocalStorage("something", "foo");

  return (
    <div>
      <div>Value: {value}</div>
      <button onClick={() => setValue("qux")}>qux</button>
      <button onClick={() => setValue("baz")}>baz</button>
      <button onClick={() => remove()}>Remove</button>
    </div>
  );
}

In the code above, 'something' is the key.

value is the value of 'something' .

setValue sets the value of 'something' .

And remove removed the entry with key 'something' .

setValue takes an argument with the value to save.

Conclusion

The react-use library lets us denounce our code, throw errors, save to local storage, and change favicons.