Categories
React Hooks

Top React Hooks — Scripts, Speech, and States

Spread the love

ks 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-script-hook

We can use the react-script-hook library to load scripts that we want to load.

To install it, we run:

npm install react-script-hook

or

yarn add react-script-hook

Then we can use it by writing:

import React from "react";
import useScript from "react-script-hook";

export default function App() {
  const [loading, error] = useScript({
    src: "https://code.jquery.com/jquery-3.5.1.js"
  });

  if (loading) return <h3>Loading jQuery...</h3>;
  if (error) return <h3>{error.message}</h3>;
  return <></>;
}

We use the useScript hook with an object as the argument.

src has the URL for the script.

It returns an array with the loading and error states.

The object also accepts an onload property with the callback to call when it’s loaded.

react-speech-kit

The react-speech-kit lets us add speech synthesis to our React app.

To install it, we run:

yarn add react-speech-kit

Then we can use it by writing:

import React from "react";
import { useSpeechSynthesis } from "react-speech-kit";

export default function App() {
  const [value, setValue] = React.useState("");
  const { speak } = useSpeechSynthesis();

  return (
    <div>
      <textarea
        value={value}
        onChange={event => setValue(event.target.value)}
      />
      <br />
      <button onClick={() => speak({ text: value })}>Speak</button>
    </div>
  );
}

We create a text area that lets us set the value of value .

Then we use the useSpeechSynthesis hook to return the speak function.

It lets us speak whatever is in the value string.

It also comes with the useSpeechRecognition hook to listen recognize speech using the Speech Recognition API built into recent browsers.

We can use it by writing:

import React from "react";
import { useSpeechRecognition } from "react-speech-kit";

export default function App() {
  const [value, setValue] = React.useState("");
  const { listen, listening, stop } = useSpeechRecognition({
    onResult: result => {
      setValue(result);
    }
  });

  return (
    <div>
      <textarea
        value={value}
        onChange={event => setValue(event.target.value)}
      />
      <br />
      <button onClick={listen}>start</button>
      <button onClick={stop}>stop</button>
      {listening && <div>listening</div>}
    </div>
  );
}

We use the useSpeechRecognition hook to let us listen to speech inputted from a microphone.

It takes an object with the onResult property that’s set to a callback.

result has the recognized speech in string form.

The listen function lets us start listening.

The stop function lets us stop listening.

listening indicates whether we’re listening or not.

react-state-patterns

The react-state-patterns package lets us create reusable states that can be used as internal states for multiple components.

To install it, we run:

npm install react-state-patterns --save

Then we can use it by writing:

import React from "react";
import useProviders, { hookSchema } from "react-state-patterns";

const { Provider, Consumer } = useProviders(props => {
  const [count, setCount] = React.useState(props.initialValue || 0);
  const handlers = {
    incrementBy: value => setCount(count + value),
    decrementBy: value => setCount(count - value)
  };
  return hookSchema({ count }, handlers, "counter");
});

export default function App() {
  return (
    <div>
      <Provider initialValue={5}>
        <Consumer>
          {({ counter: { state, handlers } }) => (
            <>
              <div>{state.count}</div>
              <button onClick={() => handlers.decrementBy(1)}>Decrement</button>
              <button onClick={() => handlers.incrementBy(1)}>Increment</button>
            </>
          )}
        </Consumer>
      </Provider>
    </div>
  );
}

We create a shared state with the useProviders function.

It takes a callback to with the props parameter and returns an object various components we can use in our components to get the state.

Provider lets us get the data that’ll set as the value of props .

We use the useState hook to set the state.

handlers is an object with functions we can call to update the state.

In App , we use the Provider and Consumer let us access the state and handlers to get and set the state respectively.

The functions that we created in the userProviders are accessed in the child of Consumer .

Conclusion

react-script-hook lets us load scripts in a React app.

react-speech-kit is a useful package for speech synthesis and recognition.

react-state-patterns lets us create reusable states easily.

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 *