circuit

Custom Hook in React for calling API — useApi




image

Introduction

In this blog we will learn about what is a custom hook and build one — useApi — to fetch data from API with reusable logic.

This blog was initially published on https://www.gyaanibuddy.com/blog/custom-hook-in-react-js-for-calling-api-useapi/
I will also soon be publishing it on GeeksforGeeks.

What is a custom hook?

A custom Hook is a JavaScript function whose name starts with “use” and that may call other Hooks. A custom hook allows you to extract some components logic into a reusable function.

In simple terms, its react way of writing reusable logic that can be shared among different components.

What are we building?

We will build a custom hook called useApi which will make the usual repetitive API fetch code reusable.

What API are we using?

We will use https://jsonplaceholder.typicode.com/users which is a free online REST API that you can use whenever you need some fake user data.

If you go to the above-mentioned URL, it will return an array of users. First, the user object’s structure is shown below.

To understand the benefits of custom hooks, let’s look at how to do do an API call

One of the most basic things we need is a way to call get data from a server and while it is being fetched from the server, we show a loading screen. We usually need this repetitively at various places on the website.

So what we usually do when we need to fetch data is:

1. Show loading screen.
2. Call the API.
3. Once we get data from server.
4. Stop loading.
5. Render/use data based on use case.

// App.js
import { useEffect, useState } from "react";

const App = () => {
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState(null);

  const fetchApi = () => {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((response) => {
        return response.json();
      })
      .then((json) => {
        console.log(json);
        setLoading(false);
        setData(json);
      });
  };

  useEffect(() => {
    fetchApi();
  }, []);

  if (loading) return <h1>Loading</h1>;

  return (
    <div>
      <h1>Data fetched successfully.</h1>
      {JSON.stringify(data)}
    </div>
  );
};

export default App;

If you print the data in the browser console, this is what the API returns.

Well, everything seems fine but think of a situation where we have a lot of Api calls in various parts of code base, in that case we need to write this fetchApi function,loading, response data logic again and again i.e we are repeating ourselves. Rather what we could do is think of a way to reuse the logic. Also the code file gets unnecessarily cluttered. That’s what brings us to the need of custom hook.

Custom Hook approach

  • Create a new file “useApi.js”. Note that it is necessary to start this name with “use”.

  • We simply pasted our **App.js **code in this file and made a few changes. One change you can see is that this returns some variables rather than JSX.

// useApi.js
import { useEffect, useState } from "react";

const useApi = (url) => {
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState(null);

  const fetchApi = () => {
    fetch(url) // 'https://jsonplaceholder.typicode.com/users'
      .then((response) => {
        return response.json();
      })
      .then((json) => {
        console.log(json);
        setLoading(false);
        setData(json);
      });
  };

  useEffect(() => {
    fetchApi();
  }, []);

  return { loading, data };
};

export default useApi;

To understand why we need this file, think of it like a file containing reusable code. This is where we have extracted the code which was going to be repeated everywhere but now it's all in one file.

All we need to do now is just call this useApi in App.js and remove the fetch logic as we have extracted it into our custom hook useApi.

New App.js

// App.js
import useApi from "./useApi";

const App = () => {
  const { loading, data } = useApi(
    "https://jsonplaceholder.typicode.com/users"
  );

  if (loading) return <h1>Loading</h1>;

  return (
    <div>
      <h1>Data fetched successfully.</h1>
      {JSON.stringify(data)}
    </div>
  );
};

export default App;

We clearly see that number of lines of code have been reduced and code looks cleaner. That’s the power of custom hooks.

You can make this hook highly customisable by adding the different parameters of the fetch API like methods, headers, body, etc, but for now, I will keep it simple for easy understanding of need and concept of custom hooks.

Done! That’s all for this blog. If you found this blog helpful, clap and share it with your friends.

References:

Codevolution React

Ben Awad React:




Continue Learning