Categories
React Hooks

Top React Hooks — Helper Hooks

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 Pirate

React Pirate is a library with various hooks we can use.

To install it, we can run:

npm install react-pirate

or:

yarn add react-pirate

It comes with various hooks, including the usePrevious hook to get the previous value of a state.

Then we can use it by writing:

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

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

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

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

We just pass in the count hook to the usePrevious hook.

It returns the previous value of count .

The useToggle hook lets us create a boolean state and toggle it.

For instance, we can write:

import React from "react";
import { useToggle } from "react-pirate";

export default function App() {
  const { value, toggle } = useToggle(false);

  return (
    <div>
      <button onClick={toggle}>toggle</button>
      <p>{value.toString()}</p>
    </div>
  );
}

to use the useToggle hook.

The hook takes a boolean as an argument.

It’s used as the initial value.

It returns an object with the value and toggle properties.

value has the value of the boolean.

toggle lets us toggle value .

The useMount hook lets us run code when the component is mounted.

For example, we can write:

import React, { useLayoutEffect } from "react";
import { useMount } from "react-pirate";

export default function App() {
  useMount(
    () => {
      console.log("mounted");
    },
    { hook: useLayoutEffect }
  );

  return <p>hello</p>;
}

We use the useMount hook with a callback in the first argument that runs when the component is mounted.

It does similar things to the componentDidMount method.

It also comes with ane equivalent to the componentDidUpdate method.

For example, we can write:

import React from "react";
import { useUpdate } from "react-pirate";

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

  useUpdate(() => {
    console.log("updated");
  });

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

We added the useUpdate hook with a callback that runs when the count state is updated.

It also comes with the useUnmount hook that takes a callback that runs a component unmounts.

We can use that by writing:

import React from "react";
import { useUnmount } from "react-pirate";

export default function App() {
  useUnmount(() => {
    console.log("unmount");
  });

  return <></>;
}

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.

For instance, we can use the useToggle hook by writing:

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

export default function App() {
  const [value, toggle] = useToggle(true);

  return (
    <>
      <button onClick={() => toggle()}>toggle</button>
      <p>{value.toString()}</p>
    </>
  );
}

We use the useToggle hook in our component.

It takes an argument for the initial value.

It returns an array with the value as the value variable.

toggle is the function to toggle value .

It comes with many more hooks to help us.

Conclusion

React Pirate and react-powerhooks both provide us many helper hooks.

Categories
React Hooks

Top React Hooks — Global State, Image Size, and Lifecycle

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-global-state

The react-hooks-global-state library lets us create global states for our React app easily.

To use it, we install it by running:

npm install react-hooks-global-state

Then we use it by writing:

import React from "react";
import { createGlobalState } from "react-hooks-global-state";

const initialState = { count: 0 };
const { useGlobalState } = createGlobalState(initialState);

const Counter = () => {
  const [count, setCount] = useGlobalState("count");
  return (
    <div>
      <span>Counter: {count}</span>
      <button onClick={() => setCount(count => count + 1)}>increment</button>
      <button onClick={() => setCount(count => count - 1)}>decrement</button>
    </div>
  );
};

export default function App() {
  return (
    <>
      <Counter />
      <Counter />
    </>
  );
}

We create a global state with the createGlobalState function.

We pass in the initialState to it to set that as the initial state.

This returns the useGlobalState hook which has the global state.

Then we can use that with the useGlobalState hook.

We pass in the state we want to get by passing in a string.

It returns an array with the state value and the function to change it in that order.

We call setCount as we do with useState ‘s state change functions.

react-hooks-image-size

The react-hooks-image-size library has a React hook for getting the size of an image.

To install it, we run:

npm install --save @use-hooks/image-size

or

yarn add @use-hooks/image-size

Then we can use it by writing:

import React from "react";
import useImageSize from "[@use](http://twitter.com/use "Twitter profile for @use")-hooks/image-size";

export default function App() {
  const url = "https://placekitten.com/g/600/600";
  const [width, height] = useImageSize(url);

  return (
    <>
      <img src={url} width={100} height={100} alt="cat" />
      <div>
        Natural size: {width} x {height}
      </div>
    </>
  );
}

The useImageSize hook returns the image’s natural width and height.

These are the values of width and height respectively.

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.

The useDidMount hook lets us run some code when the component is mounted.

For instance, we can use it by writing:

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

export default function App() {
  useDidMount(() => {
    console.log("mounted");
  });

  return <></>;
}

We use the useDidMount hook with a callback which runs when the component is mounted.

The useWillUnmount hook is the equivalent of the componentWillUnmount method of React class components.

The callback we pass in runs when the component will unmount.

For example, we can write:

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

export default function App() {
  useWillUnmount(() => {
    console.log("will unmount");
  });

  return <></>;
}

to run the callback when the component unmounts.

Conclusion

The react-hooks-global-state library lets us create a global state in our React app.

The react-hooks-image-size library gets the natural size of the image.

React Hooks Lib is a library with a bunch of reusable hooks.

Categories
React Hooks

Top React Hooks — Form, Layout, and Async

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 Hook Form

React Hook Form is a useful form library to let us add forms to a React app easily.

To install it, we run:

npm install react-hook-form

Then we can use it by writing:

import React from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const { register, handleSubmit, errors } = useForm();
  const onSubmit = data => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input name="firstname" ref={register} placeholder="first name" />
      <br />
      <input
        name="lastname"
        ref={register({ required: true })}
        placeholder="last name"
      />
      {errors.lastname && "last name is required."}
      <br />
      <input name="age" ref={register({ pattern: /d+/ })} placeholder="age" />
      {errors.age && "age must be a number"}
      <br />
      <input type="submit" />
    </form>
  );
}

We create our form with the inputs.

And we use the useForm hook to return some functions and objects we cause.

register lets us register our input so that we can use React Hook Form to do validation and handle input values.

errors has the errors for each field.

handleSubmit is a function that lets us handle submissions.

It takes a callback which we create to get the form data and do something with it.

The data parameter in onSubmit has the inputted data.

The register function takes an object with the pattern and required properties.

pattern has the validation pattern.

required indicates whether the field is required.

react-hook-layout

The react-hook-layout library lets us create layouts with a hook.

To install it, we can run:

npm install react-hook-layout

or:

yarn add react-hook-layout

Then we can use it by writing:

import React from "react";
import { defineSlots, useLayout } from "react-hook-layout";

export default function App() {
  const { Content, Footer, Header, SidebarLeft, SidebarRight } = defineSlots(
    "Content",
    "Footer",
    "Header",
    "SidebarLeft",
    "SidebarRight"
  );

  const Layout = useLayout();

  return (
    <Layout>
      <Content>content</Content>
      <Footer>footer</Footer>
      <Header>header</Header>
      <SidebarLeft>left</SidebarLeft>
      <SidebarRight>right</SidebarRight>
    </Layout>
  );
}

We use the defineSlots function to create our slots for the layout.

The arguments are the slot component names.

Then we can use the useLayout hook to create the Layout component to wrap around the slots.

react-hooks-async

The react-hooks-async library lets us make HTTP requests easily.

To install it, we run:

npm install react-hooks-async

Then we can use it by writing:

import React from "react";
import { useAsyncTask, useAsyncRun } from "react-hooks-async";

const fetchName = async ({ signal }, name) => {
  const response = await fetch(`https://api.agify.io/?name=${name}/`, {
    signal
  });
  const data = await response.json();
  return data;
};
export default function App() {
  const task = useAsyncTask(fetchName);
  useAsyncRun(task, "michael");
  const { pending, error, result, abort } = task;

  return (
    <>
      <p>{JSON.stringify(pending)}</p>
      <p>{JSON.stringify(error)}</p>
      <p>{JSON.stringify(abort)}</p>
      <p>{JSON.stringify(result)}</p>
    </>
  );
}

We created the fetchName function which takes an object with the signal property and parameters we pass in.

signal is the abort signal.

name is the parameter we want to pass in.

It returns a promise which resolves to the response data.

Then we can use the useAsyncTask hook with the fetchName function to return the task object.

We use this with the useAsyncRun hook with the argument we want to pass in.

Then task object has the pending , error , result , and abort properties.

pending indicates whether the result is pending.

error has any errors which come up.

result has the response body.

abort has the abort signal.

Conclusion

React Hook Form lets us create forms easily.

react-hook-layout lets us create layouts.

The react-hooks-async library lets us run async code with ease.

Categories
React Hooks

Top React Hooks — Fetch and State Helpers

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-fetch-hook

The react-fetch-hook lets us fetch data from an API with a hook.

Its size is small and Flow and TypeScript types are included.

To install it, we can run:

yarn add react-fetch-hook

or:

npm i react-fetch-hook --save

Then we can use it by writing:

import React from "react";
import useFetch from "react-fetch-hook";

export default function App() {
  const { isLoading, data } = useFetch("https://api.agify.io/?name=michael");

  return isLoading ? <div>Loading...</div> : <>{JSON.stringify(data)}</>;
}

We use the useFetch hook with the URL of the API endpoint we want to get data from.

The isLoading has the loading state and data has the data.

It supports error handling and do multiple requests.

We can also format our data in a custom format.

react-hanger

The react-hanger library comes with various hooks we can use to do various things.

To install it, we run:

yarn add react-hanger

We can use the useInput hook to do automatic form value binding.

For instance, we can write:

import React from "react";
import { useInput } from "react-hanger";

export default function App() {
  const newTodo = useInput("");

  return (
    <>
      <input type="text" value={newTodo.value} onChange={newTodo.onChange} />
      <p>{newTodo.value}</p>
    </>
  );
}

The useInput hook returns an object which has the value and onChange properties that we can pass into the respective props.

The useBoolean lets us toggle the value of a boolean easily.

For instance, we can write:

import React from "react";
import { useBoolean } from "react-hanger";

export default function App() {
  const showCounter = useBoolean(true);

  return (
    <>
      <button onClick={showCounter.toggle}>toggle</button>
      <p>{showCounter.value.toString()}</p>
    </>
  );
}

The useNumber hook lets us set a number as long as it’s within a range.

For instance, we can write:

import React from "react";
import { useNumber } from "react-hanger";

export default function App() {
  const limitedNumber = useNumber(3, { lowerLimit: 0, upperLimit: 5 });

  return (
    <>
      <button onClick={() => limitedNumber.increase()}> increase </button>
      <button onClick={() => limitedNumber.decrease()}> decrease </button>
      <p>{limitedNumber.value}</p>
    </>
  );
}

We have the useNumber hook with an object with the lowerLimit and upperLimit properties.

Then we can use the increase and decrease methods to change the value property of limitedNumber .

We can’t set a number beyond the given range with it.

We can also add the loop option and set it to true so that the number will loop when it reaches the limits.

If we remove the object in the 2nd argument of the hook, then the number can be set to any value:

import React from "react";
import { useNumber } from "react-hanger";

export default function App() {
  const limitedNumber = useNumber(3);

  return (
    <>
      <button onClick={() => limitedNumber.increase()}> increase </button>
      <button onClick={() => limitedNumber.decrease()}> decrease </button>
      <p>{limitedNumber.value}</p>
    </>
  );
}

Conclusion

react-fetch-hook lets us fetch data from endpoints without hassle.

Also, we can use the react-hanger hook which various state helpers.

Categories
React Hooks

Top React Hooks — Cookies, Debounce, and Clipboard

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 useCopyClipboard hook to let us copy any string to the clipboard.

For instance, we can write:

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

export default function App() {
  const [isCopied, setIsCopied] = useCopyClipboard();

  const copy = () => {
    setIsCopied("copy string");
  };

  return (
    <button onClick={copy} type="button">
      {isCopied ? "Copied" : "Copy"}
    </button>
  );
}

to create a button to copy a string to the clipboard.

The useCopyClipboard hook returns an array with the isCopied and setIsCopied variables.

isCopied indicates that the string is copied to the clipboard if it’s true .

setIsCopied copies the string to the clipboard.

The useDarkMode hook lets us toggle on and off dark mode.

The setting will be saved in local storage.

For instance, we can write:

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

export default function App() {
  const [darkMode, setDarkMode] = useDarkMode();

  return (
    <div>
      <button onClick={() => setDarkMode(!darkMode)}>toggle dark mode</button>
      <p>{darkMode.toString()}</p>
    </div>
  );
}

The setDarkMode function sets whether dark mode is on or not.

darkMode has the toggle state of dark mode.

The setting would be saved as an entry with the key dark-mode-enabled in local storage.

It doesn’t come with any styles, so we’ve to set the dark mode styles ourselves.

useDebounce is a hook that lets us denounce any fast-changing value.

For instance, we can use it by writing:

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

export default function App() {
  const [searchTerm, setSearchTerm] = React.useState("");
  const [result, setResult] = React.useState({});

  const debouncedSearchTerm = useDebounce(searchTerm, 500);

  const search = async () => {
    const res = await fetch(`https://api.agify.io/?name=${debouncedSearchTerm}`);
    const data = await res.json();
    setResult(data);
  };

  React.useEffect(() => {
    if (debouncedSearchTerm) {
      search();
    }
  }, [debouncedSearchTerm]);

  return (
    <div>
      <input value={searchTerm} onChange={e => setSearchTerm(e.target.value)} />
      <p>{JSON.stringify(result)}</p>
    </div>
  );
}

We use the useDebounce hook with the searchTerm state.

The 2nd argument is the delay to set the debouncedSearchTerm value in milliseconds.

Then we pass that into the array in the 2nd argument of useEffect to watch its value.

It’ll run the search function to get the data if debouncedSearchTerm is set.

The useDimensions hook let us get the dimension of any element.

To use it, we can write:

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

export default function App() {
  const [wrapperRef, dimensions] = useDimensions();

  return (
    <div ref={wrapperRef}>
      height: {dimensions.height}
      width: {dimensions.width}
    </div>
  );
}

The hook returns the wrapperRef that we pass as the value of the ref prop of the element that we want to watch the size of.

dimensions has the dimensions of the div that we passed the ref to.

Then as we change the size of the viewport, we’ll see the dimensions update.

Conclusion

React Recipes has hooks for rebounding, copying to clipboard, watching element sizes, and manipulating cookies.