Skip to main content

Front-End Development

React reusable API call using Custom React Hooks

Istock 1355632594

Introduction

Custom Hooks are reusable functions that let a React JS developer tailor and adjust a React application’s functionality. React JS version 16.8 includes them.

A special JavaScript function with the prefix “use” is referred to as a “Custom Hooks.”

Using a customized Hook, retrieve information from an API. This hook will return an object with the data and an optional error message given a URL. This Hook can then be utilized in a component.

 

Benefit of Custom Hooks

Code reusability: Custom Hooks enable the reuse of logic across multiple components.

Complex logic abstraction: creating custom Hooks to abstract complicated logic enhances code readability and helps components stay focused on their designated tasks.

Stateful Logic Outside of Components: with the help of custom Hooks we manage logic outside components for sharing logic to other components.

Most of the applications we create today consume data from external sources through APIs. They fetch data from the server and show it in their front end.

Getting started with Custom Hook in React

Installation

Step 1: Creating React App

npx create-react-app custom-react-hook
cd custom-react-hook
npm start

Step 2: Create a new file called useFetch.js

In this file , create a function called useFetch() this accepts a URL string a parameter.

Usefetch

This Hook should make the API call immediately after it’s called. So you can use the useEffect() Hook for this.

For the actual API calls, use the fetch API. This API is a promise-based interface that allows you to make requests and receive responses over HTTP asynchronously.

In the useFetch() custom Hook. Add the following.

import { useEffect, useState } from "react";

const useFetch = (url) => {
    const [data, setdata] = useState(null);
    const [loading, setloading] = useState(true);
    const [error, seterror] = useState("");

    useEffect(() => {
        fetch(url)
            .then((res) => res.json())
            .then((data) => {
                setdata(data)
                setloading(false)
                seterror(data.error)
            })
    }, [url]);

    return { data, loading, error };
};

export default useFetch;

In this Hook, you can be initializing the state of three values:

  • data: hold API response
  • loading: hold a boolean value that indicates whether it has fetched the API data. Initialize the loading state to true. Once the API returns data, set it to be false.
  • error: hold an error message if an error occurs.

The useEffect() Hook takes the URL string and argument. This is to ensure it runs each time the URL change.

now we create a component with the name product-list.js file to show the product list using API

product list Show in table format so we create table. And using map() method we destructor array object and show.

The useEffect() function will return an object containing the data, loading, and error values. add useFetch.js file into product-list.js

import React from 'react'
import useFetch from '../hook/useFetch';

function ProductList() {
  const { data, loading, error } = useFetch('https://dummyjson.com/products');
  if (loading) return (<div>loading...</div>)
  if (error) return (<div>error:{error.message}</div>)

  return (
    <>
      <table>
        <thead>
          <tr>
            <td></td>
            <td>Product Name</td>
            <td>Price</td>
            <td>Brand</td>
          </tr>
        </thead>
        {data.products.map((item, i) => (
          <tr key={i}>
            <td>
              <img src={item.images[0]} className='image-name' alt="product" />
            </td>
            <td>{item.title}</td>
            <td>{item.price}</td>
            <td>{item.brand}</td>
          </tr>
        ))}
      </table>
    </>
  )
}
export default ProductList

Similarly, if you want to get data from other API for another component that time also you can import useFetch.js file to another component and pass URL

import React from 'react'
import useFetch from '../hook/useFetch';

function ProductCategories() {
  const { data, loading, error } = useFetch('https://api.escuelajs.co/api/v1/categories');
  if (loading) return (<div>loading...</div>)
  if (error) return (<div>error:{error.message}</div>)
  return (
    <>
      <h1>Products Categories</h1>
      <div style={{ display: 'inline-flex' }}>{data.map((categories, i) => (
        <div key={i}>
          <img src={categories.image} className='image-name' alt="categories" />
          <h5>{categories.name}</h5>
        </div>
      ))}
      </div>
    </>)
}
export default ProductCategories

and import both components in App.js

import './App.css';
import ProductCategories from './components/product-categories';
import ProductList from './components/product-list';
function App() {
  return (
    <div className="App">
      <ProductCategories/>
      <ProductList />
    </div>
  );
}
export default App;

Folder structure:

Folder structure

Result: on http://localhost:3000

List result

 

Categories result

 

Conclusion:

With custom Hook you may build shared and reusable logic. You can create components that are more efficient, modular, and maintainable by encouraging complex logic. Try incorporating custom Hook into your project to see the improved development experience they provide.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Daivat Dharmik

With more than five years of experience, Daivat Dharmik is a front-end developer and Technical Consultant. He is well-versed in JavaScript and its various frameworks, including React, Angular, and Ionic. Daivat enjoys learning about and experimenting with the newest front-end technologies. He is passionate about developing online applications that are responsive and easy to use.

More from this Author

Follow Us
TwitterLinkedinFacebookYoutubeInstagram