In this blog post, we explore how to fetch and display multiple users' data in a React application using the useEffect hook. We walk through setting up the component, making an API request to JSONPlaceholder, storing the data using useState, and rendering it dynamically in a table. Additionally, we discuss how useEffect manages side effects efficiently and provide key takeaways for improving API handling in React.

Fetching Multiple Users' Data Using useEffect Hook in React (Part 2)

Introduction

The useEffect hook is an essential tool in React for handling side effects in functional components. In this tutorial, we will explore how to fetch and display multiple users' data from an external API using the useEffect hook. By the end of this guide, you will understand how to make API calls, store the retrieved data in state, and render it dynamically in a table format.

Understanding useEffect in React

The useEffect hook allows us to perform side effects such as fetching data, updating the DOM, and managing subscriptions. It runs after the component renders and can be configured to run only when specific dependencies change.

Fetching User Data from an API

To fetch user data, we will use the fetch method inside useEffect and store the retrieved data in the component's state using the useState hook.

Step-by-Step Implementation

1. Setting Up the Component

We start by importing the necessary hooks from React:

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

2. Creating the UserData Component

Inside our functional component, we define a state variable users to store the user data:

const UserData = () => {
  const [users, setUsers] = useState([]);

3. Fetching Data Using useEffect

We use the useEffect hook to fetch data from an API when the component mounts:

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((response) => response.json())
      .then((data) => setUsers(data));
  }, []); // Empty dependency array ensures it runs only once on mount

4. Rendering the Data in a Table

Once the data is fetched, we map through the users array and display the results in a table:

  return (
    <div>
      <h1>User List</h1>
      <table border="1" cellPadding="10px">
        <thead style={{ backgroundColor: "#f2f2f2" }}>
          <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Phone</th>
          </tr>
        </thead>
        <tbody>
          {users.map((user) => (
            <tr key={user.id}>
              <td>{user.id}</td>
              <td>{user.name}</td>
              <td>{user.email}</td>
              <td>{user.phone}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};
export default UserData;

How It Works

  1. Initial Render: The component renders, and the users state is initialized as an empty array.

  2. useEffect Execution: The useEffect hook runs after the first render, fetching data from the API.
  3. Updating State: The fetched user data is stored in the users state using setUsers.
  4. Rendering Data: The component re-renders, displaying the retrieved user information in a table format.

Key Takeaways

  • The useEffect hook is ideal for fetching data in functional components.

  • The empty dependency array [] ensures that the API call runs only once when the component mounts.
  • The fetched data is stored in state using useState and dynamically displayed in the UI.

Conclusion

By leveraging useEffect, you can efficiently fetch and display data from APIs in your React applications. This example showcases a common use case for fetching multiple users and rendering them dynamically. Experiment further by handling errors, adding loading states, or filtering users based on criteria.

Next Steps

  • Implement error handling for failed API requests.

  • Add a loading indicator to enhance user experience.
  • Explore pagination to manage large datasets efficiently.

Stay tuned for more React.js tutorials and keep building amazing applications! 🚀
To know more visit our YOUTUBE channel

Multiple-Choice Questions (MCQs)
1. What is the primary purpose of the useEffect hook in React?
A) To modify the state directly
B) To handle side effects such as data fetching
C) To create new React components dynamically
D) To define reusable styles in React

2. Why is the dependency array [] passed to useEffect in this example?
A) To ensure the effect runs only once when the component mounts
B) To make useEffect run on every render
C) To pass data from one component to another
D) To prevent the API call from executing

3. Which API is used in the example to fetch user data?
A) OpenWeather API
B) JSONPlaceholder API
C) GitHub API
D) Firebase API

4. What React hook is used to store the fetched user data?
A) useRef
B) useContext
C) useState
D) useReducer

5. What will happen if the dependency array is omitted from useEffect?
A) The API call will never execute
B) The API call will execute on every render
C) React will throw an error
D) The component will not render

6. Which method is used to convert the API response to JSON format?
A) .text()
B) .json()
C) .toJson()
D) .stringify()

7. What key is used in the map function to uniquely identify each user in the table?
A) user.email
B) user.phone
C) user.id
D) user.name

8. What happens after the data is fetched and stored using setUsers(data)?
A) The component updates and displays the new user data
B) The state remains unchanged
C) The table does not update until a manual refresh
D) The application crashes

9. What is the significance of border="1" in the <table> element?
A) It makes the table responsive
B) It adds a border around the table
C) It sets the table width to 100%
D) It prevents data from overlapping

10. What would be a good next step to improve this implementation?
A) Implement error handling for API failures
B) Remove the useEffect hook
C) Fetch data from multiple APIs simultaneously
D) Replace JSONPlaceholder with a local file

Answers
1. B) To handle side effects such as data fetching
2. A) To ensure the effect runs only once when the component mounts
3. B) JSONPlaceholder API
4. C) useState
5. B) The API call will execute on every render
6. B) .json()
7. C) user.id
8. A) The component updates and displays the new user data
9. B) It adds a border around the table
10. A) Implement error handling for API failures
 

Download Lecture Pdf..

Leave a Comment

Get a Call Back from Our Career Assistance Team Request Callback
WhatsApp