Categories
React Hooks

Top React Hooks — Swipes and States

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 Swipeable

React Swipeable is a library that lets us handle swipe events in our app.

For instance, we can write:

import React from "react";
import { useSwipeable, Swipeable } from "react-swipeable";

export default function App() {
  const handlers = useSwipeable({
    onSwiped: eventData => console.log("swiped")
  });
  return <div {...handlers}> swipe here </div>;
}

We use the useSwipeable hook which takes an object with some options.

onSwiped is a callback that runs when the we swipe on the elements with the handlers .

We can add options to the 2nd argument of the useSwipeable hook.

For instance, we can write:

import React from "react";
import { useSwipeable, Swipeable } from "react-swipeable";

export default function App() {
  const handlers = useSwipeable({
    onSwiped: eventData => console.log("swiped"),
    onSwipedLeft: eventData => console.log("swiped left"),
    onSwipedRight: eventData => console.log("swiped right"),
    onSwipedUp: eventData => console.log("swiped up"),
    onSwipedDown: eventData => console.log("swiped down"),
    onSwiping: eventData => console.log("swiping")
  });
  return <div {...handlers}> swipe here </div>;
}

to add more handlers that handlers different kinds of swiping.

React Tracked

The React Tracked is a package that lets us manage shared states.

To install it, we run:

npm install react-tracked

Then we can use it by writing:

import React from "react";
import { createContainer } from "react-tracked";

const useValue = ({ reducer, initialState }) =>
  React.useReducer(reducer, initialState);
const { Provider, useTracked } = createContainer(useValue);

const initialState = {
  count: 0
};

const reducer = (state, action) => {
  switch (action.type) {
    case "increment":
      return { ...state, count: state.count + 1 };
    case "decrement":
      return { ...state, count: state.count - 1 };
    default:
      throw new Error(`unknown action type: ${action.type}`);
  }
};

const Counter = () => {
  const [state, dispatch] = useTracked();
  return (
    <div>
      <div>
        <span>Count: {state.count}</span>
        <button type="button" onClick={() => dispatch({ type: "increment" })}>
          increment
        </button>
        <button type="button" onClick={() => dispatch({ type: "decrement" })}>
          decrement
        </button>
      </div>
    </div>
  );
};

export default function App() {
  return (
    <>
      <Provider reducer={reducer} initialState={initialState}>
        <Counter />
        <Counter />
      </Provider>
    </>
  );
}

We create the useValue function which takes the reducer and initial state and pass them to the useReducer hook.

Then we call createContainer get the value.

The reducer is like another reducer we see.

The Counter component gets and sets the state with the useTracked hook.

state has the states we have.

dispatch is a function to dispatch our actions.

Then in App , we use the Provider returns from createContainer to let us share states with the provider.

The state is accessible with anything inside.

reducer has the reducer we created earlier.

initialState has the initial state.

And we put the Counter inside it to let us get and set the shared state.

Conclusion

React Swipeable lets us watch for swipe events and handle them.

React Tracked lets us created shared states like other popular state management solutions.

Categories
React Hooks

Top React Hooks — State and Color

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-powerhooks

The react-powerhooks library comes with various hooks that we can use in our app.

To install it, we run:

yarn add react-powerhooks

Then we can use the hooks that it comes with.

The useActive lets us watch if an element is active.

The useInterval hook lets us run code periodically in our React component.

To use it, we can write:

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

export default function App() {
  const [time, setTime] = React.useState(null);
  const { start, stop } = useInterval({
    duration: 1000,
    startImmediate: false,
    callback: () => {
      setTime(new Date().toLocaleTimeString());
    }
  });

  return (
    <>
      <div>{time}</div>
      <button onClick={() => stop()}>Stop</button>
      <button onClick={() => start()}>Start</button>
    </>
  );
}

We use the useInterval hook in our app.

It takes an object with various properties.

duration is the duration of each period.

startImmediate means that the callback runs when the component loads if it’s true .

callback is the callback to run.

It returns an array with the stop and start functions to stop and start the timer respectively.

We then used that in our onClick handlers.

The useMap hook lets us manipulate key-value pairs in our component.

For instance, we can write:

import React from "react";
import { useMap } from "react-powerhooks";

export default function App() {
  const {
    set: setKey,
    get: getKey,
    has,
    delete: deleteKey,
    clear,
    reset,
    values
  } = useMap({ name: "james", age: 20 });

  return (
    <>
      <button onClick={() => setKey("foo", "bar")}>set key</button>
      <button onClick={() => deleteKey()}>delete</button>
      <button onClick={() => clear()}>clear</button>
      <button onClick={() => reset()}>reset</button>
      <div>{JSON.stringify(values)}</div>
    </>
  );
}

We used the useMap hook with an object passed in as the initial value.

It returns an object with methods or adding, getting, and removing data.

clear and reset clear the data.

deleteKey delete the data.

setKey sets the key-value pair.

React Recipes

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

To install it, we run:

npm i react-recipes --save

or:

yarn add react-recipes

Then we can use it by writing:

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

export default function App() {
  const lightGray = useAdjustColor(0.8, "#000");
  const darkerWhite = useAdjustColor(-0.4, "#fff");
  const blend = useAdjustColor(-0.2, "rgb(20,50,200)", "rgb(300,70,20)");
  const linerBlend = useAdjustColor(
    -0.5,
    "rgb(20,60,200)",
    "rgb(200,60,20)",
    true
  );

  return (
    <div>
      <div style={{ background: lightGray, height: "50px", width: "50px" }} />
      <div style={{ background: darkerWhite, height: "50px", width: "50px" }} />
      <div style={{ background: blend, height: "50px", width: "50px" }} />
      <div style={{ background: linerBlend, height: "50px", width: "50px" }} />
    </div>
  );
}

We use the useAdjustColor hook to adjust the color our way.

The first argument is the percentage between -1 and 1.

Positive is lighter and negative is darker.

The 2nd and 3rd arguments are the color code strings.

It can be hex or RGB value.

The 3rd argument is optional.

The 4th argument is the library blend, which can be hex or RGB value.

The default is false .

It returns the color string that’s created after adjusting the color.

It comes with many more hooks we can use.

Conclusion

The react-powerhooks package comes with various state management hooks.

React Recipes has color adjustment and many other kinds of hooks.

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.