Popular Searches
Popular Course Categories
Popular Courses

Fetching Data in React

Fetching Data in React

API Integration in React

Fetching Data in React

Fetching data in React is the process of requesting information from an external source, such as an API or server, and displaying the received information in a user interface. React applications commonly fetch data to display users, products, weather information, news, blog posts, and other dynamic content.

Course: JustAcademy React JS Training

Course Demo: Register for React JS Course Demo


1. What Is Data Fetching in React?

Data fetching means sending a request to a server or API to retrieve information. React then uses that information to render or update components on the screen.

For example, an e-commerce application may fetch product names, prices, images, and descriptions from a backend API instead of storing all product information directly in the component.

Common Uses of Data Fetching

  • Displaying product lists in an e-commerce application.
  • Loading user profiles and account information.
  • Fetching weather information from a weather API.
  • Displaying news articles and blog posts.
  • Loading student records from a database through a backend API.
  • Retrieving dashboard statistics and reports.

2. How Data Fetching Works in React

A typical data-fetching process follows these steps:

  1. The component is rendered.
  2. React runs an Effect when the component needs to load external data.
  3. The browser sends an HTTP request to the API.
  4. The server processes the request and sends a response.
  5. The application checks whether the request was successful.
  6. The response body is converted into JavaScript data, commonly using JSON.
  7. React state is updated with the fetched data.
  8. The component re-renders to display the updated information.

Basic Flow Diagram

React Component
      |
      v
Send API Request
      |
      v
Server / API
      |
      v
Receive Response
      |
      v
Convert Response to JSON
      |
      v
Update React State
      |
      v
Display Data in UI

3. What Is an API?

An API (Application Programming Interface) allows different software systems to communicate with each other. In React, an API often provides data from a backend server in JSON format.

Example API endpoint: https://jsonplaceholder.typicode.com/users

This public demonstration endpoint returns sample user records that can be used to practise fetching data.

Example API Response

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "email": "[email protected]"
  },
  {
    "id": 2,
    "name": "Ervin Howell",
    "email": "[email protected]"
  }
]

The response is JSON data. After parsing it, React can display each user's name and email address.

4. The Fetch API in JavaScript

The Fetch API is a built-in browser feature used to make HTTP requests. It returns a Promise that resolves to a Response object when a response is received.

Basic Fetch Example

fetch("https://jsonplaceholder.typicode.com/users")
  .then(response => {
    if (!response.ok) {
      throw new Error("Failed to fetch data");
    }
    return response.json();
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error("Error:", error);
  });

Explanation

  • fetch() sends the HTTP request.
  • response.ok checks whether the HTTP status is in the successful range.
  • response.json() parses the response body as JSON and returns a Promise.
  • .then() processes the successful result.
  • .catch() handles errors such as network failures or errors thrown in the Promise chain.

Important: Fetch does not automatically reject its Promise for HTTP errors such as 404 or 500. Check response.ok to handle unsuccessful HTTP status codes.

5. Fetching Data Using useEffect

The useEffect Hook can be used to fetch data when a component appears on the screen or when specified dependencies change. It is useful when manually synchronizing a component with an external API.

Example: Fetch Users

import { useState, useEffect } from "react";

function Users() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    const controller = new AbortController();

    async function fetchUsers() {
      try {
        setLoading(true);
        setError("");

        const response = await fetch(
          "https://jsonplaceholder.typicode.com/users",
          { signal: controller.signal }
        );

        if (!response.ok) {
          throw new Error("Unable to fetch users");
        }

        const data = await response.json();
        setUsers(data);
      } catch (err) {
        if (err.name !== "AbortError") {
          setError(err.message || "Something went wrong");
        }
      } finally {
        if (!controller.signal.aborted) {
          setLoading(false);
        }
      }
    }

    fetchUsers();

    return () => {
      controller.abort();
    };
  }, []);

  if (loading) {
    return <p>Loading users...</p>;
  }

  if (error) {
    return <p>Error: {error}</p>;
  }

  return (
    <div>
      <h2>User List</h2>
      <ul>
        {users.map(user => (
          <li key={user.id}>
            {user.name} - {user.email}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default Users;

Understanding the Code

  • useState([]) stores the fetched user records.
  • loading indicates whether the request is in progress.
  • error stores an error message if the request fails.
  • useEffect() starts the request after the component commits.
  • async/await makes asynchronous code easier to read.
  • AbortController allows the request to be cancelled during cleanup.
  • users.map() creates a list item for every user.
  • key={user.id} gives each list item a stable identifier.

6. Understanding async and await

async and await are JavaScript features that simplify working with Promises. An async function always returns a Promise, and await pauses that function until a Promise settles.

Example

async function getUsers() {
  const response = await fetch(
    "https://jsonplaceholder.typicode.com/users"
  );

  if (!response.ok) {
    throw new Error("Request failed");
  }

  const users = await response.json();
  return users;
}

Using try...catch around asynchronous requests helps handle failures clearly. Remember that an async function cannot be passed directly as the Effect callback when its returned Promise is intended to be the cleanup function; instead, define and call an asynchronous function inside the Effect.

7. Managing Loading, Success, and Error States

A reliable data-fetching component should handle more than the successful response. It should also communicate the loading status and show a helpful message when a request fails.

State Purpose Example UI
Loading Indicates that a request is in progress. Loading users...
Success Displays the retrieved data. List of users
Error Informs the user that the request failed. Unable to load users.
Empty Indicates that the request succeeded but returned no records. No users found.

Example: Empty-State Check

if (!loading && !error && users.length === 0) {
  return <p>No users found.</p>;
}

Place this check after the loading and error checks so that an unfinished request or failed request is not incorrectly presented as an empty result.

8. Fetching Data on User Interaction

Not every request should run automatically when a component mounts. If data should load only after a user clicks a button, start the request from the event handler.

Example: Load Products on Button Click

import { useState } from "react";

function Products() {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  async function loadProducts() {
    try {
      setLoading(true);
      setError("");

      const response = await fetch(
        "https://dummyjson.com/products"
      );

      if (!response.ok) {
        throw new Error("Unable to load products");
      }

      const data = await response.json();
      setProducts(data.products ?? []);
    } catch (err) {
      setError(err.message || "Request failed");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div>
      <button onClick={loadProducts} disabled={loading}>
        {loading ? "Loading..." : "Load Products"}
      </button>

      {error && <p>{error}</p>}

      <ul>
        {products.map(product => (
          <li key={product.id}>
            {product.title} - ${product.price}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default Products;

In this example, the API request begins when the user clicks the button. The sample API returns a product collection inside the products property.

9. Fetching Data When a Dependency Changes

Sometimes data depends on a value such as a user ID, category, search term, or page number. Add the reactive values used by the Effect to its dependency array so that the request updates when those values change.

Example: Fetch a User by ID

import { useEffect, useState } from "react";

function UserDetails({ userId }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    const controller = new AbortController();

    async function loadUser() {
      try {
        setLoading(true);
        setError("");
        setUser(null);

        const response = await fetch(
          `https://jsonplaceholder.typicode.com/users/${userId}`,
          { signal: controller.signal }
        );

        if (!response.ok) {
          throw new Error("User not found");
        }

        const data = await response.json();
        setUser(data);
      } catch (err) {
        if (err.name !== "AbortError") {
          setError(err.message || "Failed to load user");
        }
      } finally {
        if (!controller.signal.aborted) {
          setLoading(false);
        }
      }
    }

    loadUser();

    return () => controller.abort();
  }, [userId]);

  if (loading) return <p>Loading user...</p>;
  if (error) return <p>{error}</p>;
  if (!user) return <p>No user found.</p>;

  return (
    <div>
      <h2>{user.name}</h2>
      <p>Email: {user.email}</p>
      <p>City: {user.address.city}</p>
    </div>
  );
}

export default UserDetails;

When userId changes, the previous Effect is cleaned up and a new request begins. Cancelling an obsolete request helps prevent an outdated response from replacing the data for the current user.

10. Handling Race Conditions and Cleanup

A race condition can occur when multiple requests are started in quick succession and an older request finishes after a newer one. Without appropriate cleanup, the older response may overwrite the latest result.

Best Practices

  • Use AbortController to cancel fetch requests when appropriate.
  • Alternatively, use an ignore flag in the Effect cleanup to prevent obsolete responses from updating state.
  • Check response.ok before parsing a response that is expected to be successful.
  • Clear or update loading and error states consistently.
  • Include every reactive value used by the Effect in its dependency list.
  • Remember that React Strict Mode may run an extra setup-and-cleanup cycle in development to help reveal cleanup problems.

Example: Ignore an Obsolete Response

useEffect(() => {
  let ignore = false;

  async function loadData() {
    try {
      const response = await fetch("/api/data");

      if (!response.ok) {
        throw new Error("Request failed");
      }

      const data = await response.json();

      if (!ignore) {
        setData(data);
      }
    } catch (err) {
      if (!ignore) {
        setError(err.message);
      }
    }
  }

  loadData();

  return () => {
    ignore = true;
  };
}, []);

This pattern prevents a completed request from updating state after its Effect has been cleaned up. In a complete implementation, loading and error state should also be managed appropriately.

11. Fetch API vs Axios

Both Fetch and Axios can be used to send HTTP requests in React applications.

Feature Fetch API Axios
Installation Built into modern browsers Requires a package installation
JSON response Usually requires calling response.json() JSON response data is generally available in response.data
HTTP error handling Check response.ok manually Rejects the Promise by default for unsuccessful HTTP status codes
Request cancellation Supports AbortController Supports AbortController with current versions
Extra features Provides standard browser request capabilities Offers features such as interceptors and configurable defaults

Axios Example

import axios from "axios";

async function getUsers() {
  try {
    const response = await axios.get(
      "https://jsonplaceholder.typicode.com/users"
    );

    console.log(response.data);
  } catch (error) {
    console.error("Failed to fetch users:", error);
  }
}

Choose Fetch for straightforward requests without extra dependencies. Consider Axios when its additional features are useful for your application.

12. Common Data-Fetching Mistakes

Mistake Why It Is a Problem Solution
Not checking HTTP status A 404 or 500 response may be treated as successful by Fetch. Check response.ok.
Ignoring loading state Users may see a blank screen while waiting. Display a loading indicator.
Ignoring errors Users receive no explanation when a request fails. Use try...catch and show an error message.
Missing Effect dependencies Data may become outdated or the Effect may behave incorrectly. Declare all reactive dependencies.
No cleanup Obsolete requests may affect current state. Abort requests or ignore obsolete responses.
Using array indexes as keys unnecessarily List updates can produce incorrect item identity. Use stable identifiers such as user.id.
Fetching repeatedly without need Creates extra network traffic and may slow the UI. Review dependencies and consider caching.
Putting secrets in frontend code Client-side code can be inspected by users. Keep private credentials on a secure server.

13. Performance and Modern Data-Fetching Approaches

Fetching directly inside useEffect is useful for learning and simple client-side cases, but it is not always the best approach for a production application.

  • Framework data fetching: Use a React framework's supported data-loading approach when available.
  • TanStack Query: Helps manage server state, caching, refetching, and request status.
  • SWR: Provides caching and revalidation features for remote data.
  • React Router: Provides route-based data-loading features in supported versions.
  • Pagination: Retrieve a subset of records instead of loading a very large dataset at once.
  • Debouncing: For search fields, delay requests until the user pauses typing when appropriate.

These tools can reduce repetitive request-management code and improve caching and loading behavior. They are optional tools, not built-in React Hooks.

14. Practical Project: User Directory

Project objective: Build a small React application that retrieves users from an API and displays their names, email addresses, and cities.

Project Requirements

  1. Create a React component named UserDirectory.
  2. Fetch records from https://jsonplaceholder.typicode.com/users.
  3. Store the response in state using useState.
  4. Use useEffect to start the request when the component mounts.
  5. Display a loading message while the request is pending.
  6. Display a helpful error message if the request fails.
  7. Show each user's name, email, and city after loading succeeds.
  8. Use each user's ID as the list item's key.
  9. Add a search input to filter users by name.

Expected Output

User Directory
------------------------------
Search: [________________]

Leanne Graham
Email: [email protected]
City: Gwenborough

Ervin Howell
Email: [email protected]
City: Wisokyburgh

The displayed sample values illustrate the intended layout. The actual values come from the API response.

15. Interview Questions and Answers

Q1. What is data fetching in React?

Data fetching is the process of retrieving information from an API or server and using it in a React component.

Q2. What is the Fetch API?

The Fetch API is a browser feature that sends HTTP requests and returns Promises containing response objects.

Q3. Why is useEffect used for data fetching?

It can synchronize a component with an external API when the component is displayed or when specified dependencies change.

Q4. Why do we use useState?

useState stores information such as fetched data, loading status, and error messages. Updating state causes React to render the updated UI.

Q5. What is the purpose of response.json()?

It reads and parses the response body as JSON and returns a Promise containing the parsed JavaScript value.

Q6. Does Fetch throw an error for a 404 response?

No. Fetch normally resolves with a Response object for HTTP errors. Check response.ok and handle unsuccessful statuses explicitly.

Q7. What is the purpose of AbortController?

It can cancel supported requests, such as a Fetch request, when the result is no longer needed.

Q8. What is a race condition in data fetching?

It occurs when requests finish in an unexpected order, allowing an outdated response to overwrite more recent data unless handled properly.

Q9. What is the difference between Fetch and Axios?

Fetch is built into modern browsers, while Axios is an external library with additional conveniences such as interceptors and configurable defaults.

Q10. Is useEffect always the best choice for data fetching?

No. Framework-provided data loading or tools such as TanStack Query and SWR may provide better caching, request coordination, and loading management for larger applications.

16. Practice Exercises

  • Fetch a list of posts and display their titles.
  • Fetch a single user by ID.
  • Add loading, success, error, and empty states to a data-fetching component.
  • Create a button that reloads the data when clicked.
  • Build a product list using https://dummyjson.com/products.
  • Add a search box to filter fetched records.
  • Cancel obsolete requests when a selected ID changes.
  • Compare a basic Fetch implementation with an Axios implementation.

17. Best Practices Checklist

  • Use the appropriate data-fetching method for your React framework or application.
  • Handle loading, success, error, and empty states.
  • Check HTTP status codes before assuming a request succeeded.
  • Use async/await or Promise methods consistently.
  • Declare all necessary Effect dependencies.
  • Clean up requests or ignore obsolete responses when needed.
  • Use stable keys when rendering lists.
  • Avoid exposing private API credentials in frontend code.
  • Consider caching and request deduplication for larger applications.
  • Test the component with successful responses, empty results, and failed requests.

18. Official Documentation and Learning Resources

Conclusion

Fetching data is an essential skill for building dynamic React applications. By understanding APIs, the Fetch API, useEffect, useState, asynchronous JavaScript, loading and error states, and request cleanup, you can build interfaces that display live data reliably. For larger applications, consider framework data-loading features or a data-fetching library to manage caching and request behavior.

Learn more through JustAcademy React JS Training or Register for React JS Course Demo.

Previous Next
whatsapp