Hackernoon logoCustom Hook in React for calling API — useApi by@rugved

Custom Hook in React for calling API — useApi

image
Rugved Bongale Hacker Noon profile picture

@rugvedRugved Bongale

Developer

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.

useApi — to fetch data from API with reusable logic.

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 component's logic into a reusable function.

In simple terms, it is the 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.

image

To understand the benefits of custom hooks, let’s look at how to 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 the server.
  4. Stop loading.
  5. Render/use data based on the 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.

image

Well, everything seems fine but think of a situation where we have a lot of API calls in various parts of the code base. In that case, we need to write this fetchApi function, loading, response data logic again and again. We 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 for a 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 as 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 has been reduced and the 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 the 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.

This blog was initially published at https://www.gyaanibuddy.com/blog/custom-hook-in-react-js-for-calling-api-useapi/

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.