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.

Categories
React Hooks

Top React Hooks — Async, Clipboard, and Cookie

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.

useAsyncRetry

The useAsyncRetry hook lets us run async cod with an addition rety method to let us retry or refresh the async function.

To use it, we run:

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

export default function App() {
  const state = useAsyncRetry(async () => {
    const response = await fetch("https://api.agify.io/?name=michael");
    const result = await response.json();
    return result;
  }, []);

  return (
    <div>
      <button onClick={() => state.retry()}>load</button>
      {(() => {
        if (state.loading) {
          return <div>Loading...</div>;
        }

        if (state.error) {
          return <div>Error</div>;
        }

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

The useAsyncRetry hook takes a callback that gets data from an API.

A promise is returned and it resolves to the response body.

The state is returned by the hook.

It has the retry method to let us get the data again.

Also, it has the loading and error properties to get the loading state and error respectively.

value has the response body.

useBeforeUnload

The useBeforeUnload hook lets us show a browser alert when the user tries to reload or close the page.

To use it, we can write:

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

export default function App() {
  useBeforeUnload(true, "You sure you want to leave");

  return <div />;
}

We pass in true to the first argument to enable the alert when we leave.

Then we add a string to show the content.

Most browsers don’t let us show custom text in the alert, so we can put in anything.

useCookie

useCookie is a hook that lets us return the current value of a cookie.

It also lets us update and delete the cookie.

For instance, we can use it by writing:

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

export default function App() {
  const [value, updateCookie, deleteCookie] = useCookie("count-cookie");
  const [counter, setCounter] = React.useState(1);

  React.useEffect(() => {
    deleteCookie();
  }, []);

  const updateCookieHandler = () => {
    updateCookie(counter);
    setCounter(c => c + 1);
  };

  return (
    <div>
      <p>Value: {value}</p>
      <button onClick={updateCookieHandler}>Update Cookie</button>
      <br />
      <button onClick={deleteCookie}>Delete Cookie</button>
    </div>
  );
}

We call the useCookie hook with the key of the cookie to let us get, set, and delete the cookie.

value has the value.

updateCookie is a function to let us update the cookie.

deleteCookie lets us delete the cookie.

Then we used that in the useEffect callback to clear the cookie on load.

And we used updateCookie when we click the Update Cookie button.

useCopyToClipboard

The useCopyToClipboard hook lets us copy text in a string to the clipboard.

For instance, we can use it by writing:

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

export default function App() {
  const [text, setText] = React.useState("");
  const [state, copyToClipboard] = useCopyToClipboard();

  return (
    <div>
      <input value={text} onChange={e => setText(e.target.value)} />
      <button type="button" onClick={() => copyToClipboard(text)}>
        copy text
      </button>
      {state.error ? (
        <p>{state.error.message}</p>
      ) : (
        state.value && <p>Copied {state.value}</p>
      )}
    </div>
  );
}

We called the useCopyToClipboard hook to return the state and copyToClipboard variables.

state is the state of the clipboard.

copyToClipboard lets us copy the text we pass into it to the clipboard.

Conclusion

The react-use library provides us with hooks to copy data to the clipboard, create cookies, and run promises.

Categories
React Hooks

Top React Hooks — Timers, Key Presses, 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 Recipes

React Recipes comes with many hooks that we can use to do various things.

The useInterval hook lets us run a piece of code periodically.

For instance, we can write:

import React from "react";
import { useInterval } from "react-recipes";

export default function App() {
  const [count, setCount] = React.useState(0);
  useInterval(
    () => {
      setCount(count => count + 1);
    },
    1000,
    true
  );

  return <div>{count}</div>;
}

We have the useInterval hook.

The callback is what’s run after a period.

The 2nd argument is the period.

The 3rd is whether we run the callback on mount or not.

We can use the useIsClient hook to check if JavaScript is loaded on the client-side or not.

For instance, we can write:

import React from "react";
import { useIsClient } from "react-recipes";

export default function App() {
  const isClient = useIsClient();

  return <div>{isClient && "client side rendered"}</div>;
}

We call the useIsClient hook which returns a boolean which indicates that the code is loaded from the client-side if it’s true .

The useKeyPress hook lets us add keydown and keyup listeners to any key.

For instance, we can write:

import React from "react";
import { useKeyPress } from "react-recipes";

export default function App() {
  const hPress = useKeyPress("h");

  return <div>{hPress && "h key pressed"}</div>;
}

We use the useKeyPress hook by passing in a string with the key we want to watch form.

If the ‘h’ key is pressed, the hPress is true .

The useLocalStorage hook lets us set and store values in local storage.

For example, we can write:

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

export default function App() {
  const [name, setName] = useLocalStorage("name", "james");

  return (
    <div>
      <input
        type="text"
        placeholder="Enter your name"
        value={name}
        onChange={e => setName(e.target.value)}
      />
    </div>
  );
}

We use the useLocalStorage hook with the key and value to store.

It returns an array with the state and the function to set the state in this order.

The state will be automatically saved in local storage.

The useLockBodyScroll hook lets us local the scrolling.

It’s handy for creating things like modals.

For example, we can write:

import React from "react";
import { useLockBodyScroll } from "react-recipes";

function Modal({ title, children, onClose }) {
  useLockBodyScroll();

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal">
        <h2>{title}</h2>
        <p>{children}</p>
      </div>
    </div>
  );
}

export default function App() {
  const [isOpen, setIsOpen] = React.useState(false);

  return (
    <>
      <button onClick={() => setIsOpen(true)}>open modal</button>
      {isOpen && (
        <Modal title="The title" onClose={() => setIsOpen(false)}>
          modal content
        </Modal>
      )}
    </>
  );
}

We use the useLockBodyScroll hook without any arguments in the Modal component.

Then we can use Modal in App to toggle it on and off.

Conclusion

React Recipes comes with hooks for running code periodically, locking scrolling, setting local storage, and watching key presses.