Categories
React Hooks

Top React Hooks — Fetch, Scroll, and Modals

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.

fetch-suspense

We can use the fetch-suspense package to do fetch and display a loading component while the data is loading.

To use it, we can install it by running:

npm install fetch-suspense

or:

yarn add fetch-suspense

Then we can use it by writing:

index.js

import React, { Suspense } from "react";
import ReactDOM from "react-dom";

import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <Suspense fallback={<p>Loading...</p>}>
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </Suspense>,
  rootElement
);

App.js

import useFetch from "fetch-suspense";
import React from "react";

export default function App() {
  const response = useFetch("https://api.agify.io/?name=michael", {
    method: "GET"
  });

  return <div className="App">{JSON.stringify(response)}</div>;
}

We add the Suspense component to the root component with the fallback component in the fallback prop.

Then in App , we use the useFetch hook to fetch the data we want.

The response is returned in the function.

Modali

The Modali package is a library for creating a modal.

We install it by running:

npm install --save modali

Then we can use it by writing:

import React from "react";
import Modali, { useModali } from "modali";

export default function App() {
  const [exampleModal, toggleExampleModal] = useModali();

  return (
    <div className="app">
      <button onClick={toggleExampleModal}>Click me</button>
      <Modali.Modal {...exampleModal}>Hello world</Modali.Modal>
    </div>
  );
}

We use the useModali hook to return the props for the Modali.Modal component.

The toggleExampleModal function is used to toggle the opening of the modal.

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

Then we can use it by writing:

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

export default function App() {
  const ref = React.useRef();
  useOutsideClick(ref, () => console.log(" clicked outside"));
  return (
    <div className="app" ref={ref}>
      hello
    </div>
  );
}

We use the useOutsideClick hook by passing in the ref of the component that we want to check whether we clicked outside.

It also comes with the useArray hook to make handling state arrays easier.

We can use it to create a state array.

And we can use it to update the array with the functions returned by the hook.

For instance, we can write:

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

export default function App() {
  const [list, actions] = useArray(["new item"]);

  return (
    <div className="app">
      <button onClick={() => actions.push("new item")}>add</button>
      {list.map(l => (
        <p>{l}</p>
      ))}
    </div>
  );
}

We have the actions object, which has array methods like push to add a new item to the array.

list has the array itself.

actions also has the removeIndex function to let us remove an item by its index.

The useLockBodyScroll hook disables scrolling on the body.

For instance, we can use it by writing:

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

export default function App() {
  useLockBodyScroll(true);
  return (
    <div className="app">
      {Array(1000)
        .fill()
        .map((_, i) => (
          <p>{i}</p>
        ))}
    </div>
  );
}

We called the useLockBodyScroll hook with argument true to disable scrolling on the body.

Now we can’t scroll even if a list of items displayed that overflow the body.

Conclusion

fetch-suspense lets us the Suspense component while fetching data.

Modali is a hook for creating modals.

moment-hooks has many hooks that help us with various things

Categories
React Hooks

Top React Hooks — Browser APIs

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.

@21kb/react-device-orientation-hook

The @21kb/react-device-orientation-hook lets us get the orientation and angle of the screen.

To use it, we install it by running:

npm install --save @21kb/react-device-orientation-hook

or:

yarn add @21kb/react-device-orientation-hook

Then we can use it by writing:

import React from "react";
import useOrientation from "@21kb/react-device-orientation-hook";

export default function App() {
  const state = useOrientation({
    angle: 0,
    type: "landscape-primary"
  });
  const { angle, type } = state;

  return (
    <div className="App">
      {angle} {type}
    </div>
  );
}

We set the default angle and orientation with the type property.

Then we can get that returned with the useOrientation hook.

@21kb/react-notification-hook

We can use the notification hook to show native notifications with our browser.

To install it, we run:

npm install --save @21kb/react-notification-hook

or:

yarn add @21kb/react-notification-hook

Then we can use it by writing:

import React from "react";
import useNotification from "@21kb/react-notification-hook";

export default function App() {
  const notify = useNotification({
    title: "hello world",
    options: {
      dir: "rtl"
    }
  });

  return <button onClick={notify()}>Notify me!</button>;
}

The useNotificatiin hook returns a function to let us display a notification.

The title has the title of the notification.

options include the dir for the direction.

@21kb/react-online-status-hook

The @21kb/react-online-status-hook package lets us get the online status of our app.

We can use the useOnlineStatus or useOfflineStatus hook to get the online status.

We install it with:

npm install --save @21kb/react-online-status-hook

Then we can use it by writing:

import React from "react";
import { useOnlineStatus } from "[@21kb/react-online-status-hook](http://twitter.com/21kb/react-online-status-hook "Twitter profile for @21kb/react-online-status-hook")";
export default function App() {
  const status = useOnlineStatus();

  return <div>You are currently {status ? "online" : "offline"}.</div>;
}

useOfflineStatus does the same thing.

For example, we can write:

import React from "react";
import { useOfflineStatus } from "@21kb/react-online-status-hook";
export default function App() {
  const status = useOfflineStatus();

  return <div>You are currently {status ? "online" : "offline"}.</div>;
}

@21kb/react-page-visible-hook

The @21kb/react-page-visible-hook package provides us with a hook for getting the page visibility status of our app.

To install it, we run:

npm install --save @21kb/react-page-visible-hook

or:

yarn add @21kb/react-page-visible-hook

to install it.

Then we can use it by writing:

import React from "react";
import useVisible from "@21kb/react-page-visible-hook";

export default function App() {
  const state = useVisible();
  const { visibilityState } = state;

  return <>{visibilityState}</>;
}

The useVisible hook returns the visibility state of our app.

The value can be 'visible' or 'prerender' .

@21kb/react-dom-status-hook

The @21kb/react-dom-status-hook package provides us with a hook to get the ready state of our app.

We can install it by running:

npm install --save @21kb/react-dom-status-hook

or:

yarn add @21kb/react-dom-status-hook

Then we can use the useDomStatus hook by writing:

import React from "react";
import useDomStatus from "@21kb/react-dom-status-hook";

export default function App() {
  const { readyState } = useDomStatus();

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

It returns an object with the readyState property to get the DOM loading state.

Conclusion

We can use various hooks to use various browser APIs.