+91 9404 340 614    gyaanibuddy@gmail.com

Like
2 Likes

Custom hook in react js for calling API - useApi

Last updated on June 2, 2021, 5:07 a.m. by rugved

In this blog we will learn about what is a custom hook and build one - 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 components logic into a reusable function.

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

I will also soon be publishing it on GeeksforGeeks

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 array of users. First user object’s structure is shown below.

To understand the benefits of custom hook, lets look how do we usually do an API call

One of the most basic thing we need is a way to call get data from server and while it being fetched from server , we show loading screen. We usually need this repetitively at various places in 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 will 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 its 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 different parameters of 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 like and share it with your friends.

References:
Codevolution react js:
https://www.youtube.com/channel/UC80PWRj_ZU8Zu0HSMNVwKWw

Ben Awad react js: 
https://www.youtube.com/playlist?list=PLN3n1USn4xlntqksY83W3997mmQPrUmqM

...

by rugved
KJ Somaiya College of Engineering Mumbai

Avid learner
blog comments powered by Disqus