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.

Categories
React Hooks

Top React Hooks — State Utilities

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.

moment-hooks

The moment-hooks library is a library that comes with various utility hooks that we can use.

We can install it with:

yarn install moment-hooks

The useDebounce hook lets us add denounce functionality to our app.

It can be used to reduce the number of times a state is updated.

For instance, we can write:

import React from "react";
import { useDebounce } from "moment-hooks";

export default function App() {
  const [inputValue] = React.useState("something");
  const debouncedInputValue = useDebounce(inputValue, 100);

  return <div className="app">{debouncedInputValue}</div>;
}

We have the useDebounce hook that takes the inputValue state.

The 2nd argument is the number of milliseconds to delay the update of the state.

The useWindowSize hook lets us get the width and height of the window.

To use it, we write:

import React from "react";
import { useWindowSize } from "moment-hooks";

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

  return (
    <div className="app">
      {width} x {height}
    </div>
  );
}

We call the useWindowSize hook to get the window’s width and height.

Then we can use those anywhere.

The useWhyDidYouUpdate hook gets the reason why a component has been updated.

It’s useful for debugging our components.

To use it, we can write:

import React from "react";
import { useWhyDidYouUpdate } from "moment-hooks";

const Foo = props => {
  useWhyDidYouUpdate("Register", props);

  return <div />;
};

export default function App() {
  return (
    <div className="app">
      <Foo foo="bar" />
    </div>
  );
}

Then since we have the useWhyDidYouUpdate hook has been called with 'Register' and props , it’ll log the value when the props are changed.

We’ll get the old and new value logged.

Nice Hooks

Nice Hooks is a set of hooks that does various things.

To install it, we run:

npm install nice-hooks

Then we can use the hooks that comes with it.

The useStateCB hook lets us get and set a state.

To use it, we can write:

import React from "react";
import { useStateCB } from "nice-hooks";

export default function App() {
  const [getCount, setCount] = useStateCB(0);

  function doSomething() {
    console.log(getCount());
  }

  return (
    <div>
      <p>{getCount()}</p>
      <button onClick={() => setCount(getCount() + 1, doSomething)}>
        Increase
      </button>
    </div>
  );
}

We use the useStateCB hook to return a getter and setter function for a state.

When we click the button, we call setCount to set the count.

doSomething is run after the state change is done.

getCount gets the count state.

The useSingleState hook is another hook that lets us get and set the state.

For instance, we can write:

import React from "react";
import { useSingleState } from "nice-hooks";

export default function App() {
  const [state, setState] = useSingleState({
    count: 0
  });

  function doSomething() {
    console.log(state.count);
  }

  return (
    <div>
      <p>{state.count}</p>

      <button
        type="button"
        onClick={() =>
          setState(
            {
              count: state.count + 1
            },
            doSomething
          )
        }
      >
        Increase
      </button>
    </div>
  );
}

useSingleState is another hook that returns that state and a setter for the state respectively.

setState takes an object to update the state.

It also takes a callback that runs when the state update is done.

Conclusion

monent-hooks and Nice Hooks are libraries that provide us with many hooks.