Categories
React Hooks

Top React Hooks — Speech, Throttling, and Scrolling

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.

We can use the useSpeechSynthesis hook lets us add speech synthesis to our React app.

For instance, we can write:

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

export default function App() {
  const [value] = React.useState("hello world");
  const [ended, setEnded] = React.useState(false);
  const onEnd = () => setEnded(true);
  const { cancel, speak, speaking, supported, voices } = useSpeechSynthesis({
    onEnd
  });

  if (!supported) {
    return "Speech is not supported. Upgrade your browser";
  }

  return (
    <div>
      <button onClick={() => speak({ text: value, voice: voices[0] })}>
        Speak
      </button>
      <button onClick={cancel}>Cancel</button>
      <p>{speaking && "Voice is speaking"}</p>
      <p>{ended && "Voice has ended"}</p>
    </div>
  );
}

We have the useSpeechSynthesis hook to return an object with various properties.

cancel cancels speech synthesis.

speak makes the computer start speaking.

speaking indicates that it’s speaking.

supported indicates whether speech synthesis is supported.

voices has the voices we can choose from.

We use it in the speak function.

The useThrottle hook lets us throttle value to change only after a given number of milliseconds.

For instance, we can write:

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

const Count = ({ count }) => {
  const throttledCount = useThrottle(count, 950);

  return (
    <>
      <div>Value: {count}</div>
      <div>Throttled value: {throttledCount}</div>
    </>
  );
};

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

  return (
    <>
      <Count count={count} />
    </>
  );
}

We have the Count component which we have the useThrottle hook to watch the count prop.

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

The useWhyDidYouUpdate lets us watch why a component updates.

For example, we can write:

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

const Counter = React.memo(props => {
  useWhyDidYouUpdate("Counter", props);
  return <div>{props.count}</div>;
});

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

  return (
    <>
      <button onClick={() => setCount(count => count + 1)}>increment</button>
      <p>
        <Counter count={count} />
      </p>
    </>
  );
}

to watch the count prop updating.

We used the useWhyDidYouUpdate to watch for the prop value changes.

The argument is the name we add to the log.

The 2nd is the value.

The useWindowScroll hook lets us re-render on window scroll.

For example, we can write:

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

export default function App() {
  const { x, y } = useWindowScroll();

  return (
    <>
      <div style={{ position: "fixed" }}>
        <div>x: {x}</div>
        <div>y: {y}</div>
      </div>
      {Array(1000)
        .fill()
        .map((_, i) => (
          <p>{i}</p>
        ))}
    </>
  );
}

We have the useWindowScroll to watch for the scroll position in our React component.

It returns and x and y coordinate for the scroll position.

Conclusion

React Recipes lets us add speech synthesis capabilities to our app.

We can also use it to throttle and watch for prop changes, and also watch for scroll positions.

Categories
React Hooks

Top React Hooks — Select and SVG Canvas

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 Hooks Lib

React Hooks Lib is a library that has many reusable React hooks.

To install it, we can run:

npm i react-hooks-lib --save

Then we can use the hooks that come with the library.

We can use the useField prop to bind the selected value to a state.

For instance, we can write:

import React from "react";
import { useField } from "react-hooks-lib";

export default function App() {
  const { value, bind } = useField("apple");

  return (
    <div>
      <select {...bind}>
        <option value="apple">apple</option>
        <option value="orange">orange</option>
        <option value="grape">grape</option>
      </select>
      <p>{value}</p>
    </div>
  );
}

We have the useField hook with the initial value for the select element.

bind is an object with the value and onChange handlers to automatically bind to the select box.

value has the value selected from the dropdown.

It comes with many other hooks for manipulating other kinds of states like arrays and also watches for DOM element changes.

Also, it has hooks to imitate the lifecycle methods of React class components.

react-hooks-svgdrawing

The react-hooks-svgdrawing library lets us create a drawing area in our app easily.

We can install it by running:

yarn add react react-hooks-svgdrawing

Then we can use it by writing:

import React from "react";
import { useSvgDrawing } from "react-hooks-svgdrawing";

export default function App() {
  const [renderRef, draw] = useSvgDrawing();
  return <div style={{ width: 500, height: 500 }} ref={renderRef} />;
}

Then renderRef is passed into the div as the ref prop’s value to make the div a drawing area.

The hook can take an object with various options.

For instance, we can write:

import React from "react";
import { useSvgDrawing } from "react-hooks-svgdrawing";

export default function App() {
  const [renderRef, draw] = useSvgDrawing({
    penWidth: 10,
    penColor: "red",
    close: true,
    curve: false,
    delay: 60,
    fill: ""
  });
  return <div style={{ width: 500, height: 500 }} ref={renderRef} />;
}

penWidth has the pen’s width.

penColor has the pen’s color.

close set to true means the drawing path will be closed.

curve use the curve command for the path.

delay is the number of milliseconds to wait before drawing a point.

fill has the fill of the path.

It comes with various methods we can use.

They’re part of the draw method.

For example, we can write:

import React from "react";
import { useSvgDrawing } from "react-hooks-svgdrawing";

export default function App() {
  const [renderRef, draw] = useSvgDrawing();
  return (
    <>
      <button onClick={() => draw.download("png")}>download</button>
      <button onClick={() => draw.undo()}>undo</button>
      <button onClick={() => draw.changePenColor("red")}>changePenColor</button>
      <button onClick={() => draw.changePenWidth(10)}>changePenWidth</button>
      <button onClick={() => draw.changeFill("green")}>changeFill</button>
      <button onClick={() => draw.changeDelay(10)}>changeDelay</button>
      <button onClick={() => draw.changeCurve(false)}>changeCurve</button>
      <button onClick={() => draw.changeClose(true)}>changeClose</button>
      <div style={{ width: 500, height: 500 }} ref={renderRef} />
    </>
  );
}

to call various methods of draw .

download downloads the drawing with the given format.

undo undoes the last change.

changePenColor changes the pen color.

changePenWidth changes the pen width.

changeFill changes the fill of the pen.

changeDelay changes the delay of drawing the dots.

changeCurve set whether to use a curved comma for the SVG path element.

chnageClose set whether to close a path.

We can use the getSvgXML method to get the SVG code.

Conclusion

React Hooks Lib has the useField and many other useful hooks.

react-hooks-svgdrawing provides us with a drawing area that is configurable.

We can download the drawing and get the SVG code from it.

Categories
React Hooks

Top React Hooks — Scripts, Speech, and States

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.

Categories
React Hooks

Top React Hooks — Previous State, Online Status and Scripts

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 useMedia hook lets us add media queries in JavaScript.

For instance, we can write:

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

export default function App() {
  const columnCount = useMedia(
    ["(min-width: 1500px)", "(min-width: 1000px)", "(min-width: 600px)"],
    [5, 4, 3],
    2
  );

  return (
    <div style={{ columns: columnCount }}>
      {Array(1000)
        .fill()
        .map((_, i) => (
          <p>{i}</p>
        ))}
    </div>
  );
}

We have the useMedia hook to set the media query.

The first argument is an array of media queries.

The 2nd is the array of values for each media query.

The 3rd is the default value to return.

Then we can use the returned value as we wish.

In the example above, we used the media queries to set the number of columns.

The useOnClickOutside hook lets us listen for clicks outside an element.

For instance, we can write:

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

export default function App() {
  const ref = React.useRef();
  const [isModalOpen, setModalOpen] = React.useState(false);

  useOnClickOutside(ref, () => setModalOpen(false));

  return (
    <div>
      {isModalOpen ? (
        <div ref={ref}>modal</div>
      ) : (
        <button onClick={() => setModalOpen(true)}>Open Modal</button>
      )}
    </div>
  );
}

We used the useOnClickOutside hook with a ref.

The ref is passed to the element that we want to watch for clicks outside.

The hook takes a callback to run some code when we click outside an element.

The useOnlineStatus hook lets us listen for the online or offline events to see the current status.

For instance, we can use it by writing:

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

export default function App() {
  const onlineStatus = useOnlineStatus();

  return (
    <div>
      <h1>{onlineStatus ? "Online" : "Offline"}</h1>
    </div>
  );
}

We called the useOnlineStatus hook to listen to the online status.

The usePrevious hook lets us get the previously set value of a state.

For example, we can write:

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

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

  const prevCount = usePrevious(count);

  return (
    <div>
      <p>
        Now: {count}, before: {prevCount}
      </p>
      <button onClick={() => setCount(count => count + 1)}>Increment</button>
    </div>
  );
}

We use the usePrevious hook with the count state to return the count state’s previous value.

prevCount has the previous value of count .

The useScript hook lets us create a scrip tag with our code.

For instance, we can write:

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

export default function App() {
  const [loaded, error] = useScript(
    "https://code.jquery.com/jquery-2.2.4.min.js"
  );

  return (
    <div>
      <div>
        Script loaded: <b>{loaded.toString()}</b>
      </div>
      {loaded && !error && (
        <div>
          Script function call response: <b>{$().jquery}</b>
        </div>
      )}
    </div>
  );
}

We called the useScript hook with the URL for our script.

We loaded jQuery and get the jQuery version with $().jquery .

loaded indicates that it’s loaded if it’s true ,

error has the error if there’s one.

Conclusion

React Recipes lets us use media queries, load scripts, watch online status, and get the previous value of a state.

Categories
React Hooks

Top React Hooks — Portal and Flux

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 Cool Portal

React Cool Portal lets us render our elements outside the usual DOM hierarchy determined by React.

To install it, we run:

yarn add react-cool-portal

or:

npm install --save react-cool-portal

Then we can use it by writing:

import React from "react";
import usePortal from "react-cool-portal";

export default function App() {
  const { Portal } = usePortal();

  return (
    <div>
      <Portal>
        <p>hello world </p>
      </Portal>
    </div>
  );
}

We called the usePortal hook to return the Portal component.

Then we can render our elements inside the Portal .

By default, the elements inside will be attached to the body.

We can add the ID of the container with the containerId .

If the element with the given ID doesn’t exist, it’ll create it for us.

For instance, we can write:

import React from "react";
import usePortal from "react-cool-portal";

export default function App() {
  const { Portal } = usePortal({ containerId: "portal" });

  return (
    <div>
      <Portal>
        <p>hello world </p>
      </Portal>
    </div>
  );
}

It also comes with states that we can use to determine whether we show or hide the element in the portal.

For example, we can write:

import React from "react";
import usePortal from "react-cool-portal";

export default function App() {
  const { Portal, isShow, show, hide, toggle } = usePortal({
    defaultShow: false,
    onShow: e => {
      // ...
    },
    onHide: e => {
      // ...
    }
  });

  return (
    <div>
      <button onClick={show}>Open</button>
      <button onClick={hide}>Close</button>
      <button onClick={toggle}>{isShow ? "Close" : "Open"} Modal</button>
      <Portal>
        <div class="modal" tabIndex={-1}>
          <div>
            <h5>Modal title</h5>
            <p>Modal body.</p>
          </div>
        </div>
      </Portal>
    </div>
  );
}

We used the userPotal hook to get more properties from the returned object.

It returns the show and hide functions to show and hide the portal.

toggle is a function to toggle the portal.

isShow has the state to indicate whether the portal is shown or not.

defaultShow sets whether the portal elements are shown by default or not.

onShow is the function to run something when the portal is shown.

onHide is the function that runs when the portal is hidden.

react-enhanced-reducer-hook

The react-enhanced-reducer-hook library lets us create a centralized data store in our app.

It’s inspired by Redux and works similarly to it.

To install it, we run:

npm install react-enhanced-reducer-hook --save

Then we can use it by writing:

import React from "react";
import useEnhancedReducer from "react-enhanced-reducer-hook";

function logMiddleware({ getState }) {
  return next => action => {
    console.log("Prev State:", getState());
    console.log("Action:", action);
    next(action);
    console.log("Next State:", getState());
  };
}

function useAppReducer(reducer, inititalState) {
  return useEnhancedReducer(reducer, inititalState, [logMiddleware]);
}

function counterReducer(state, action) {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
    case "reset":
      return { count: 0 };
    default:
      return state;
  }
}

export default function App() {
  const [state, dispatch] = useAppReducer(counterReducer, { count: 0 });
  return (
    <React.Fragment>
      <button onClick={() => dispatch({ type: "increment" })}>increment</button>
      <button onClick={() => dispatch({ type: "decrement" })}>decrement</button>
      <button onClick={() => dispatch({ type: "reset" })}>reset</button>
      <br />
      Count: {state.count}
    </React.Fragment>
  );
}

We have the useAppReducer hook, which we pass the counterReducer into it.

The hook is created by us by using the useEnhancedReducer hook where we pass the reducer, initial state, and any middleware that we want to run into it.

We return the results of useEnhancedReducer so that we can use it in our component.

The Redux reducer is like any other reducer.

We have the logMiddleware that we can run during state changes.

In App , we get the state and dispatch variables.

state has the current state.

And dispatch has the function to dispatch our actions.

The type is the action type.

Then we get the count state with state.count .

Conclusion

React Cool Portal lets us create portals without the hassle.

The react-enhanced-reducer-hook library lets us create a centralized data store.

The library is inspired by Redux.