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.

Categories
React Hooks

Top React Hooks — Touch and Context

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.

Melting Pot

Melting Pot has a bunch of hooks that we can use in our React app.

It’s a utility library with many hooks.

To install it, we run:

npm install @withvoid/melting-pot --save

or:

yarn add @withvoid/melting-pot

The useTouch hook lets us watch for the touching of an element.

To use it, we can write:

import React from "react";
import { useTouch } from "@withvoid/melting-pot";

export default function App() {
  const { touched, bind } = useTouch();

  return (
    <div {...bind}>
      <p>Touch this</p>
      <p>
        Status: <span>{String(touched)}</span>
      </p>
    </div>
  );
}

We use the useTouch hook, which returns an object with the touched and bind properties.

touched indicates whether the item is touched.

bind is an object which we use as props for the element we want to watch for touches.

The useUpdate hook us a replacement of the componentDidUpdate method in React class components.

We can use it by writing:

import React from "react";
import { useUpdate } from "@withvoid/melting-pot";

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

  useUpdate({
    action: () => console.log("state was updated"),
    exit: () => console.log("exiting")
  });
  return (
    <div>
      <button onClick={() => setCount(count + 1)}>{count}</button>
    </div>
  );
}

We can use the useUpdate hook to watch for state updates.

We used the hook with an object passed into it.

action runs when the state is updated.

exit runs when it rerenders.

The useWindowScrollPosition hook lets us watch for the scroll position on our page.

We can use it by writing:

import React from "react";
import { useWindowScrollPosition } from "@withvoid/melting-pot";

export default function App() {
  const scrollPosition = useWindowScrollPosition();

  return (
    <div>
      <p style={{ position: "fixed" }}>{JSON.stringify(scrollPosition)}</p>
      {Array(1000)
        .fill()
        .map((_, i) => (
          <p>{i}</p>
        ))}
    </div>
  );
}

We watch for the scroll position with the hook.

It has the x and y properties to show the scroll position’s x and y coordinates.

Now as we scroll, we’ll see the position update.

The useWindowSize hook lets us watch for the size of the window.

To use it, we write:

import React from "react";
import { useWindowSize } from "[@withvoid/melting-pot](http://twitter.com/withvoid/melting-pot "Twitter profile for @withvoid/melting-pot")";

export default function App() {
  const { width, height } = useWindowSize();
  return (
    <div>
      {width} x {height}
    </div>
  );
}

The width and height has the width and height of the window.

Constate

The Constate library lets us share data between components by lifting the state to the top with the context API.

We can install it by running:

npm i constate

or:

yarn add constate

Then we can write:

import React, { useState } from "react";
import constate from "constate";

function useCounter() {
  const [count, setCount] = useState(0);
  const increment = () => setCount(prevCount => prevCount + 1);
  return { count, increment };
}

const [CounterProvider, useCounterContext] = constate(useCounter);

function Button() {
  const { increment } = useCounterContext();
  return <button onClick={increment}>increment</button>;
}

function Count() {
  const { count } = useCounterContext();
  return <span>{count}</span>;
}

export default function App() {
  return (
    <div>
      <CounterProvider>
        <Count />
        <Button />
      </CounterProvider>
    </div>
  );
}

to use it.

We created ou own useCounter hook to update the count state.

It returns the state and a function to update it.

Then we use constate to create a context with the hook.

It returns the context provider and a hook to use the context.

Then in Button and Counter , we call useCounterContext to use the state.

It just returns what we return in the useCounter hook.

Then we can use the components together in App without passing props around.

The CounterProvider is the context provider and it has to wrap around everything.

Conclusion

Melting Pot has various useful hooks.

Constant lets us share context state in an orderly way.