Categories
React Hooks

Top React Hooks — Clipboard, APIs, and Forms

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-use-clipboard

The react-use-clipboard library provides us with copy to clipboard functionality.

To install it, we run:

npm install react-use-clipboard --save-exact

or

yarn add react-use-clipboard --exact

Then we can use it by writing:

import React from "react";
import useClipboard from "react-use-clipboard";

export default function App() {
  const [isCopied, setCopied] = useClipboard("hello world");

  return (
    <button onClick={setCopied}>{isCopied ? "copied" : "not copied"}</button>
  );
}

We use the useClipboard hook with a string argument to let us copy it to the clipboard.

isCopied is a boolean to indicate whether it’s copied or not.

setCopied lets us copy the text to the clipboard.

We can reset the isCopied state after a period of time.

To do that, we can pass an object into the 2nd argument with the successDuration property:

import React from "react";
import useClipboard from "react-use-clipboard";

export default function App() {
  const [isCopied, setCopied] = useClipboard("hello world", {
    successDuration: 1000
  });

  return (
    <button onClick={setCopied}>{isCopied ? "copied" : "not copied"}</button>
  );
}

The number is in milliseconds.

react-use-data-loader

The react-use-data-loader library lets us load data with logic outside our component.

To install it, we run:

npm install --save react-use-data-loader

or:

yarn add react-use-data-loader

Then we can use it by writing;

import React from "react";
import { useDataLoader } from "react-use-data-loader";

async function getData(name) {
  const res = await fetch(`https://api.agify.io/?name=${name}`);
  const data = await res.json();
  return data;
}

export default function App() {
  const { data, error, loading, retry } = useDataLoader(getData, "michael");

  if (loading) {
    return <div>loading...</div>;
  }

  if (error) {
    return <div>Error</div>;
  }

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

We have the getData function which returns a promise with the response body.

Then we can pass that into the useDataLoader hook so that we can get the data we want with it.

The 2nd argument of the hook is passed to the parameter of the getData function.

It returns the data , error , loading and retry properties.

data has the resolved data.

error has the errors object.

loading has the loading state.

react-use-form-state

The react-use-form-state library lets us create forms without hassle.

To install it, we run:

npm install --save react-use-form-state

Then we can use it by writing:

import React from "react";
import { useFormState } from "react-use-form-state";

export default function App() {
  const [formState, { text, email, password, radio }] = useFormState();

  function handleSubmit(e) {
    e.preventDefault();
    console.log(formState.values);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input {...text("name")} placeholder="name" />
      <input {...email("email")} required placeholder="email" />
      <input
        {...password("password")}
        required
        minLength="8"
        placeholder="password"
      />
      <br />
      <input {...radio("plan", "free")} /> free
      <input {...radio("plan", "premium")} /> premium
      <br />
      <input type="submit" />
    </form>
  );
}

We use the useFormStare hook to create our form.

It returns an object with the formState with the form’s state, including the values, pristine, dirty, etc.

text , email , password , and radio are functions that we can call to add the type of input with the given name.

It returns an object with the value and form handler, which we can use in our input.

The first argument of these functions are the value of the name attribute.

The 2nd argument is the value of the value attribute.

Then we can get the form values with the formState.values .

Conclusion

react-use-clipboard lets us copy data to the clipboard.

react-use-data-loader lets us load data from APIs with ease.

react-use-form-state lets us create forms without the usual hard work.

Categories
React Hooks

Top React Hooks — Calendar, Form, and API

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

The react-uniformed package lets us create forms with ease.

To install it, we run:

npm install --save react-uniformed

or:

yarn add react-uniformed

to install it.

Then we can use it by writing:

import React from "react";
import { useForm, useSettersAsEventHandler } from "react-uniformed";

export default function App() {
  const { setValue, values, submit } = useForm({
    onSubmit: data => console.log(data)
  });

  const handleChange = useSettersAsEventHandler(setValue);

  return (
    <>
      <form onSubmit={submit}>
        <label>Name</label>
        <input name="name" value={values.name} onChange={handleChange} />

<button>Submit</button>
      </form>
    </>
  );
}

We created a basic form with the form element.

The useForm hook takes an object with the onSubmit method.

data has the data we submit.

The object it returns has the setValue , values , and submit properties.

setValue is used with the useSettersAsEventHandler hook to get the change handler function.

The submit function is passed into the submit prop.

React Use API

React Use API is another library that lets us make HTTP requests cleanly.

To use it, we run:

npm i react-use-api axios

or:

yarn add react-use-api axios

to install it.

Then we can use it by writing:

index.js

import React from "react";
import ReactDOM from "react-dom";
import { ApiProvider } from "react-use-api";

import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <ApiProvider>
    <App />
  </ApiProvider>,
  rootElement
);

App.js

import React from "react";
import useApi from "react-use-api";

export default function App() {
  const [data, { loading, error }, request] = useApi({
    url: "https://api.agify.io?name=michael"
  });

  return (
    <>
      {loading && <div>Loading...</div>}
      {error && <div>{error.response.data.errMsg}</div>}
      {data && <>{JSON.stringify(data)}</>}
    </>
  );
}

We import the ApiProvider that wraps around the App component.

Then we can use the useApi hook by passing in an object with the url to the API.

That returns the data , loading , error and request objects.

data has the response body.

loading has the request loading state.

error has the error object.

request is a function that lets us make the request again.

react-use-calendar

The react-use-calendar library is a library that lets us add a calendar to our app.

To use it, we run:

npm install react-use-calendar --save

to install it.

Then we write:

import React from "react";
import useCalendar from "react-use-calendar";

export default function App() {
  const [state, actions] = useCalendar(null, {
    events: [
      {
        startDate: new Date(2020, 8, 27),
        endDate: new Date(2020, 8, 27),
        note: "meeting"
      },
      {
        startDate: new Date(2020, 8, 22),
        endDate: new Date(2020, 8, 25),
        note: "vacation"
      }
    ]
  });

  return (
    <table>
      <thead>
        <tr>
          <td colSpan={5} style={{ textAlign: "center" }}>
            <strong>
              {state.month} - {state.year}
            </strong>
          </td>
          <td colSpan={2} style={{ textAlign: "right" }}>
            <button onClick={() => actions.getPrevMonth()}>&lt;</button>
            <button onClick={() => actions.getNextMonth()}>&gt;</button>
          </td>
        </tr>
        <tr>
          {state.days.map(day => (
            <th key={day}>{day}</th>
          ))}
        </tr>
      </thead>
      <tbody>
        {state.weeks.map((week, index) => (
          <tr key={index}>
            {week.map(day => (
              <td
                key={day.dayOfMonth}
                style={{
                  textAlign: "center",
                  backgroundColor: day.isToday ? "orange" : "#fff"
                }}
              >
                {day.dayOfMonth}
              </td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
}

to use it.

We display the calendar with today’s date displayed in orange.

events is an array with calendar events.

We’ve to render the calendar and events ourselves with our own table.

Conclusion

react-uniformed lets us create a simple form.

React Use API lets us make API requests.

react-use-calendar is a hook that lets us create a calendar.

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.