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.

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.