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.

Categories
React Hooks

Top React Hooks — States and Requests

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.

Hookstate

We can use the Hookstate hook to change global and local state in our app.

To use it, we run:

npm install --save @hookstate/core

or:

yarn add @hookstate/core

to install it.

Then we can manage global state by writing:

import React from "react";
import { createState, useState } from "@hookstate/core";
const globalState = createState(0);

export default function App() {
  const state = useState(globalState);
  return (
    <>
      <p>Counter value: {state.get()}</p>
      <button onClick={() => state.set(p => p + 1)}>Increment</button>
    </>
  );
}

We create a global state object with the createState function and then pass it into the Hookstate’s useState hook.

Then we can use get and set to get and set the state respectively.

To change local state, we can write:

import React from "react";
import { useState } from "@hookstate/core";

export default function App() {
  const state = useState(0);
  return (
    <>
      <p>Counter value: {state.get()}</p>
      <button onClick={() => state.set(p => p + 1)}>Increment</button>
    </>
  );
}

The only difference is that we pass the state value straight into the useState hook.

States can be nested.

For example, we can write:

import React from "react";
import { useState, self } from "@hookstate/core";

export default function App() {
  const state = useState([{ name: "Untitled" }]);

console.log(state);
  return (
    <>
      {state.map((task, index) => (
        <p>
          {task.name.get()} {index}
        </p>
      ))}
      <button onClick={() => state[self].merge([{ name: "Untitled" }])}>
        add task
      </button>
    </>
  );
}

We use the useState hook with an array.

To add new value to the array, we use the state[self] object’s merge method to add an entry to it.

Then we can get the entry by using the property’s get method as we did in the map callback.

We can also add scoped, async, and recursive states.

We can use the @jzone/react-request-hook to help us make requests easier.

We can install it by running:

npm install @jzone/react-request-hook

or:

yarn add @jzone/react-request-hook

Then we can use it by writing:

import React from "react";
import useFetchData from "@jzone/react-request-hook";
import axios from "axios";

export default function App() {
  const [{ data, isLoading, error }, fetchData] = useFetchData(data =>
    axios.get("https://api.agify.io/?name=michael", { params: data })
  );

  React.useEffect(() => {
    fetchData();
  }, [fetchData]);

  if (!data) {
    return !error ? <div>loading...</div> : <div>error</div>;
  }

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

We imported the useFetchData hook to import the hook.

Also, we installed Axios to use that as an HTTP client.

Then we use the fetchData function returned by the hook to get the data.

The data has the response data.

So we can render that the way we want.

It also returns the isLoading state to indicate loading.

error has the error.

We can customize it for other kinds of requests.

Conclusion

Hookstate is a useful hook for managing states.

@jzone/react-request-hook is a hook that lets us get data easier.