React Js- Fetch Data From API Using Hooks


 In my last article, we discussed Fetch data from API and display in table React Js. In this post, We will discuss, How to Fetch Data From an API Using React Hooks.

Hooks are the latest feature introduced to the React 16.8. Hooks allow us to use state and other React features without using a class component. Hooks are the functions that allow us to use the React state and lifecycle features in function components.

we can’t use Hooks inside the class component, hooks are only used in function components. Hooks do not contain any breaking changes and it does not replace your understanding of React concepts.Hook uses useState() function for setting and retrieving state in the function component.

We are going to consumpe the below API for showing the demo.

API ENDPOINT:https://reqres.in/api/users?page=2

Response:

{
"page": 2,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 7,
"email": "[email protected]",
"first_name": "Michael",
"last_name": "Lawson",
"avatar": "https://reqres.in/img/faces/7-image.jpg"
},
{
"id": 8,
"email": "[email protected]",
"first_name": "Lindsay",
"last_name": "Ferguson",
"avatar": "https://reqres.in/img/faces/8-image.jpg"
},
{
"id": 9,
"email": "[email protected]",
"first_name": "Tobias",
"last_name": "Funke",
"avatar": "https://reqres.in/img/faces/9-image.jpg"
},
{
"id": 10,
"email": "[email protected]",
"first_name": "Byron",
"last_name": "Fields",
"avatar": "https://reqres.in/img/faces/10-image.jpg"
},
{
"id": 11,
"email": "[email protected]",
"first_name": "George",
"last_name": "Edwards",
"avatar": "https://reqres.in/img/faces/11-image.jpg"
},
{
"id": 12,
"email": "[email protected]",
"first_name": "Rachel",
"last_name": "Howell",
"avatar": "https://reqres.in/img/faces/12-image.jpg"
}
]
}

React Js Code

import React, { useState, useEffect } from "react";

const Userlist = () => {
const [userList, setusers] = useState(null);
  useEffect(() => {
    getuesers();
  }, []);
const getuesers = () => {
    fetch("https://reqres.in/api/users?page=2")
      .then((res) => res.json())
      .then(
        (result) => {
          console.log(result.data);
          setusers(result.data);
        },
        (error) => {
          console.log(error);
          setusers(null);
        }
      );
  };
if (!userList) return <div>No Record Found</div>;
return (
    <div>
      <h2>users List using Hooks</h2>
      <table className="table">
        <thead>
          <tr>
            <th>User Id</th>
            <th>Name</th>
            <th>Address</th>
            <th>City</th>
            <th>ZipCode</th>
          </tr>
        </thead>
        <tbody>
          {userList.map((user) => (
            <tr>
              <td>{user.id}</td>
              <td>
                <img
                  src={user.avatar}
                  style={{ height: "50px", borderRadius: "50%" }}
                ></img>{" "}
              </td>
              <td>{user.email}</td>
              <td>{user.first_name}</td>
              <td>{user.last_name}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};
export default Userlist;

react fetch data from api hooks

Functional Component Definition:The Userlist component is defined as an arrow function.a state variable userList is declared using the useState hook. It will hold the list of users fetched from the API.The useEffect hook is utilized to perform side effects in the component. It's used here to fetch the list of users from a specified API endpoint (https://reqres.in/api/users?page=2) when the component mounts. The getusers function is called inside the useEffect hook.

Fetch Data Function: This function is defined to make a GET request to the specified URL. Upon receiving a response, it logs the result data to the console and updates the userList state with the fetched data. If there's an error during the request, it logs the error and sets userList to null.

If userList is null, it renders a message saying "No Record Found". This handles cases where data hasn't been fetched yet or if there's an error fetching the data.

Otherwise, it renders a table displaying the list of users. Each user's details such as id, avatar, email, first name, and last name are displayed in separate table cells.

This component fetches a list of users from an API and displays their details in a table format. It uses React hooks for state management and performing side effects.

If you looking to create a function component, and you want to use maintain state, previously before React 16.8 we need to create the class component do. But, now after the introduction of Hooks, we can do using a Hook inside our function component so that we don’t need to convert the functional component into the class component.

I’m assuming that you are familiar with React Js framework and creating React Js applications. If not then please go through the following articles:

React Js is the most popular and famous library in the field of web development. It is used by very large companies, such as Netflix, Instagram, Airbnb, etc.

React Js comes with a lot of features, that’s why it is used more than others like some frameworks, AngularJS, etc.

React JS is an open-source, front-end JavaScript library from which UI interfaces are created adnd It is a declarative, efficient, and flexible Javascript library using which reusable UI components are created.

As I mentioned earlier, it is an open-source, component-based frontend library using which the view layer of the application is created.

It was created by Facebook and is managed by Facebook itself and it is also used to make other Facebook products such as Instagram and WhatsApp.

Using React js, the user interface is broken down into smaller components, which are very easy to handle.

I hope that from this post, you must have got complete information about fetching data in React JS using hooks.

If you have any query or you want tell us anything more about React JS, then feel free to comment to us, we will be very happy to help you and learn something new from you.