Categories
React Hooks

Top React Hooks — Async and Window

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 useWindowSize hook lets watch the size of the window as it changes.

For instance, we can write:

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

export default function App() {
  const { width, height } = useWindowSize();

  return (
    <div>
      {width}x{height}
    </div>
  );
}

We call the useWindowSize hook to return the width and height properties.

They’re the width and height of the window.

We can also pass in the initial width and height, which are useful for server-side rendered apps.

It comes with many other useful hooks to make our lives easier.

React Request Hook

The React Request Hook library lets us make requests with ease.

To install it, we run:

yarn add react-request-hook axios

or:

npm install --save react-request-hook axios

Then we can use it by writing:

index.js

import React from "react";
import ReactDOM from "react-dom";
import { RequestProvider } from "react-request-hook";
import axios from "axios";
import App from "./App";

const axiosInstance = axios.create({
  baseURL: "https://api.agify.io/"
});

const rootElement = document.getElementById("root");
ReactDOM.render(
  <React.StrictMode>
    <RequestProvider value={axiosInstance}>
      <App />
    </RequestProvider>
  </React.StrictMode>,
  rootElement
);

App.js

import React from "react";
import { useResource } from "react-request-hook";

export default function App() {
  const [name, getName] = useResource(name => ({
    url: `/?name=${name}`,
    method: "get"
  }));

  React.useEffect(() => {
    getName("michael");
  }, []);

  return <div>{JSON.stringify(name)}</div>;
}

In index.js , we create the Axios instance and pass it into the RequestProvider component.

The value prop takes the Axios instance.

Then we can use the useResource hook in App to get the data we want.

In the callback we pass in, we return the url and method .

The url is the path relative to the URL in the Axios instance.

method is the request method.

It returns an array with the result and the function to get the result.

name has the response body.

And getName is a function that takes the same parameter as the useResource callback to get the data.

Then we can call getName to get the data.

It also provides us with other ways to make requests.

React-RocketJump

React-RocketJump is another library that lets us commit async side effects in our React app.

To use it, we install it by running:

yarn add react-rocketjump

Then we can use it by writing:

import React from "react";
import { rj, useRunRj } from "react-rocketjump";

const NameState = rj({
  effect: () => fetch(`https://api.agify.io/?name=michael`).then(r => r.json())
});

export default function App() {
  const [{ data: name, pending, error }] = useRunRj(NameState);

  return (
    <>
      {error && <div>Got some troubles</div>}
      {pending && <div>Wait...</div>}
      {JSON.stringify(name)}
    </>
  );
}

We create our side effect with the rj function.

The object has the effect method which returns a promise with the data.

Then in App , we use the useRunRj hook to get the data.

We pass in NameState as the argument of the hook.

Then it returns an array with an object that has the data , pending , and error properties.

data has the response body.

pending has the pending status.

error has the error.

Conclusion

React Recipes, React Request Hook, and React-RocketJump are all useful libraries that give us various hooks to do what we want.

Categories
React Hooks

Top React Hooks — Arrays and Inputs

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.

The useList hook lets us create a state array and manipulate it.

For instance, we can write:

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

export default function App() {
  const { list, sort, filter } = useList([13, 5, 7, 4, 4, 6, 5, 7, 3.3, 6]);

  return (
    <div>
      <button onClick={() => sort((x, y) => x - y)}>sort</button>
      <button onClick={() => filter(x => x >= 5)}>
        greater than or equal to 5
      </button>
      <p>{JSON.stringify(list)}</p>
    </div>
  );
}

The useList hook takes an array as the argument.

This is used as the initial value of the list state.

The returned object also has the sort and filter methods to let us sort the list array.

The useFetch hook lets us make HTTP requests to a server.

For instance, we can write:

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

export default function App() {
  const getUrl = name => `https://api.agify.io/?name=${name}`;
  const { value, bind } = useField("michael");
  const { data, loading, setUrl } = useFetch(getUrl("michael"));
  return (
    <div>
      <h3>useFetch</h3>
      <input type="text" value={value} {...bind} />
      <button
        onClick={() => {
          setUrl(getUrl(value));
        }}
      >
        search
      </button>
      {loading ? <div>Loading...</div> : <>{JSON.stringify(data)}</>}
    </div>
  );
}

We created our own getUrl function that returns the full URL for our requests.

useField is a hook that takes the default value of the input box.

value has the value of the input.

bind has the props for the input to bind the input onChange function to update the parameter of getUrl .

When we click the button, we call setUrl to set the URL.

This is one of the methods returned by the useFetch hook.

Once it’s set, the request will be made, and the data property has the response body.

loading has the loading state.

The useHover hook lets us track the hover status of an element.

To use it, we can write:

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

export default function App() {
  const { hovered, bind } = useHover();
  return (
    <div>
      <div {...bind}>
        hovered:
        {String(hovered)}
      </div>
    </div>
  );
}

to use the useHover hook.

We pass the bind object to the div as its props to watch its hover state.

Then we get the hover state with the hovered property.

We can use the useField to help us handle input data easily and bind it 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("something");

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

We use the useField hook with an initial value for the input.

The returned object has the value with the inputted value.

bind is an object with the onChange and value properties that let us handle the input values and set it to a state.

Conclusion

React Hooks Lib lets us manipulate arrays and bind input values easily.

Categories
React Hooks

Top React Hooks — Arrays and Cookies

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.

One hook that it comes with is the useArray hook.

To use it, we can write:

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

export default function App() {
  const { add, clear, removeIndex, removeById, value: currentArray } = useArray(
    ["cat", "dog", "bird"]
  );

  return (
    <>
      <button onClick={() => add("chicken")}>Add animal</button>
      <button onClick={() => removeIndex(currentArray.length - 1)}>
        Remove animal
      </button>
      <button onClick={clear}>Clear</button>
      <p>{currentArray.join(", ")}</p>
    </>
  );
}

The useArray hook takes an array as the initial value of the array.

It returns an object with various properties.

add is a function that lets us add an item.

clear is a function to clear the array.

removeIndex is a function to remove an entry by its index.

removeById lets us remove an item by its id property.

The useAsync hook lets us run async code in a cleaner way.

We cab separate our async code into its own function.

For example, we can write:

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

const draw = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const rnd = Math.random() * 10;
      rnd <= 5 ? resolve(rnd) : reject("error");
    }, 2000);
  });
};

export default function App() {
  const { error, execute, pending, value } = useAsync(draw, false);

  return (
    <div>
      <button onClick={execute} disabled={pending}>
        {pending ? "Loading..." : "Click Me"}
      </button>
      {value && <div>{value}</div>}
      {error && <div>{error}</div>}
    </div>
  );
}

to use the hook.

We have the useAsync hook that takes the draw function.

draw returns a promise that resolves to a random value or rejects the promise depending on the value of rnd .

The 2nd argument of the hook is whether we let the hook run immediately.

The hook returns an object with various properties.

error is a string that comes from the rejected promise.

execute is a function to delay the execution of our function.

pending is a boolean to indicate when it’s executing.

value is the value returned from the execution of our function.

The useCookie hook lets us manipulate client-side cookies.

To use it, we can write:

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

export default function App() {
  const [userToken, setUserToken, deleteUserToken] = useCookie("token", "0");

  return (
    <div>
      <p>{userToken}</p>
      <button onClick={() => setUserToken("100")}>Change token</button>
      <button onClick={() => deleteUserToken()}>Delete token</button>
    </div>
  );
}

to use the useCookie hook.

The arguments for the hook are the key and initial value of the cookie.

It returns an array with some variables we can use.

userToken is the token value.

setUserToken is the function to set the cookie with the key token .

deleteUserToken deletes the cookie with the token key.

Conclusion

React Recipes comes with hooks for manipulation arrays and cookies.

Categories
React Hooks

Top React Hooks — Workers, Local Storage, and Sizes

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.

useWorker

The useWorker hook lets us use web workers easily in our React app.

To install it, we run:

npm install --save @koale/useworker

Then we can use it by writing:

import React from "react";
import { useWorker } from "@koale/useworker";

const numbers = [...Array(1000000)].map(e => Math.random() * 1000000);
const sortNumbers = nums => nums.sort();

export default function App() {
  const [sortWorker] = useWorker(sortNumbers);

  const runSort = async () => {
    const result = await sortWorker(numbers);
    console.log("End.");
  };

  return (
    <>
      <button type="button" onClick={runSort}>
        Run Sort
      </button>
    </>
  );
}

We have a large numbers array that we want to sort.

We want to do this in the background so that we can use our app to do something else.

Once we click the button, tjhe runSort function runs, which uses the sortWorker function to do the sorting.

We just pass our long-running function we want to run with useWorker .

Once it’s done, we’ll log 'End.' to indicate that it’s done.

@rehooks/component-size

@rehooks/component-size is a hook that lets us get the size of a component.

To use it, we run:

yarn add @rehooks/component-size

to install it.

Then we use it by writing:

import React from "react";
import useComponentSize from "@rehooks/component-size";

export default function App() {
  const ref = React.useRef(null);
  const size = useComponentSize(ref);
  const { width, height } = size;
  let imgUrl = `https://via.placeholder.com/${width}x${height}`;

  return (
    <div>
      <img ref={ref} src={imgUrl} style={{ width: "100vw", height: "100vh" }} />
    </div>
  );
}

We set the image size to fill the whole screen.

We pass the ref into the image so that we can get the image size with the useComponentSize hook.

Then the width and height will have the latest width and height values of the image.

rehooks/document-visibility

We can use the rehooks/document-visibility package to get the visibility of a page.

To use it, we run:

yarn add @rehooks/document-visibility

to install it.

Then we can use it by writing:

import React from "react";
import useDocumentVisibility from "@rehooks/document-visibility";

export default function App() {
  const documentVisibility = useDocumentVisibility();

  return <div>{documentVisibility}</div>;
}

We just call the hook and then get the visibility value.

@rehooks/input-value

The @rehooks/input-value package has a hook to let us bind input values to a state automatically.

To install it we run:

yarn add @rehooks/input-value

Then we can write:

import React from "react";
import useInputValue from "@rehooks/input-value";

export default function App() {
  let name = useInputValue("mary");
  return (
    <>
      <p>{name.value}</p>
      <input {...name} />
    </>
  );
}

to use it.

We get the value that’s inputted with the value property.

And we pass all the properties as props of the input.

We pass in the default value to the hook.

@rehooks/local-storage

The @rehooks/local-storage lets us manipulate local storage in our React app with some hooks.

To install it, we run:

yarn add @rehooks/local-storage

or:

npm i @rehooks/local-storage --save

Then we can use it by writing:

import React from "react";
import { writeStorage, useLocalStorage } from "@rehooks/local-storage";

export default function App() {
  const [counterValue] = useLocalStorage("i", 0);
  return (
    <>
      <p>{counterValue}</p>
      <button onClick={() => writeStorage("i", counterValue + 1)}>
        increment
      </button>
    </>
  );
}

We get the value with the useLocalStorage hook.

The first argument is the key. The 2nd is the initial value.

writeStorage lets us write the value with the given key and the value respectively.

Conclusion

There are useful for getting component sizes, manipulating local storage, and binding input values.

Categories
React Hooks

Top React Hooks — Website Data

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.

@d2k/react-devto

@d2k/react-devto is a package that provides us with hooks that give us content from dev.to.

To install it, we run:

npm i @d2k/react-devto --save

Then we can use the provided hooks by writing;

import React from "react";
import {
  useArticles,
  useFollowSuggestions,
  useTags,
  useUser
} from "@d2k/react-devto";
export default function App() {
  const { articles, loading, error } = useArticles();

  return (
    <>
      <div>{articles.map(a => a.title)}</div>
      <div>{loading}</div>
      <div>{error}</div>
    </>
  );
}

It provides the useArticles hook to get the latest articles.

articles has the articles’ data.

loading has the loading state.

error has errors if any.

It can take the page , tag , and username arguments in this order.

page is the page to go to.

tag is the tag to search for.

username has the username to look for.

The useTags hook has the tags from the website.

We can use it by writing:

import React from "react";
import {
  useArticles,
  useFollowSuggestions,
  useTags,
  useUser
} from "@d2k/react-devto";
export default function App() {
  const { tags, loading, error } = useTags();

  return (
    <>
      <div>
        {tags.map(t => (
          <p>{t.name}</p>
        ))}
      </div>
    </>
  );
}

@d2k/react-github

@d2k/react-github is a series of React hooks that let us get data from Github.

To install it, we run:

npm i @d2k/react-github --save

Then we can use it by writing:

import React from "react";
import { useUser } from "@d2k/react-github";

export default function App() {
  const { user, loading, error } = useUser("nat");

  return (
    <>
      <div>{JSON.stringify(user)}</div>
    </>
  );
}

We can pass the user name into the useUser hook to get its data.

It includes the ID, login, company, and more.

The useRepos hook let us get the repos that a user has.

For example, we can write:

import React from "react";
import { useRepos } from "@d2k/react-github";

export default function App() {
  const { repos, loading, error } = useRepos("nat");

  return (
    <>
      <div>{JSON.stringify(repos)}</div>
    </>
  );
}

We have the useRepos hook to get the repos of the 'nat' user.

The useBranch hook lets us get data about a branch of the repo.

To use it, we write:

import React from "react";
import { useBranch } from "@d2k/react-github";

export default function App() {
  const { branch, loading, error } = useBranch("facebook", "react", "master");

  return (
    <>
      <div>{JSON.stringify(branch)}</div>
    </>
  );
}

We get the repo with the user name, repo name, and the branch name in this order.

There’s also the useBranches hook to get data from all branches of a repo.

For example, we can write:

import React from "react";
import { useBranches } from "@d2k/react-github";

export default function App() {
  const { branches, loading, error } = useBranches("facebook", "react");

  return (
    <>
      <div>{JSON.stringify(branches)}</div>
    </>
  );
}

In all examples, loading and error have the loading and error states.

Conclusion

We can use some useful hooks to get public data from various websites.