Popular Searches
Popular Course Categories
Popular Courses

Fetching Data with Effects

Fetching Data with Effects

React Side Effects and Lifecycle

Fetching Data with Effects in React

Fetching Data with Effects is a React technique used to retrieve data from an API or external server using the useEffect() Hook. The fetched data is usually stored in state with useState() and displayed in the user interface.

These notes cover API requests, loading states, error handling, dependency arrays, cleanup functions, race conditions, practical examples, and best practices.

Course: JustAcademy React JS Training
Course Demo: Register for React JS Course Demo


1. What Is Data Fetching in React?

Data fetching means requesting information from an external source, such as a REST API, and using that information in a React application. Instead of hardcoding all information into the component, an application can retrieve updated data from a server.

For example, a React application may fetch:

  • User profiles and account details.
  • Product information from an e-commerce API.
  • Weather information from a weather API.
  • News articles from a news API.
  • Posts, comments, and tasks from a backend server.
  • Student records from an educational platform.

2. What Is useEffect()?

useEffect() is a React Hook that synchronizes a component with an external system. Network requests are one common use case for Effects.

Syntax:

useEffect(() => {
  // Perform the side effect
  return () => {
    // Optional cleanup
  };
}, [dependencies]);

When fetching data, the Effect can request information after the component renders, process the response, and update state. React then renders the component again with the new data.

3. Why Do We Use Effects for Data Fetching?

Effects are useful when a component should keep its displayed data synchronized with external information based on its current props or state.

  • Automatic fetching: Fetch data when a component appears or a relevant dependency changes.
  • Dynamic content: Display information retrieved from an API.
  • State management: Store the response in React state.
  • Refresh on changes: Fetch updated information when a user ID, search query, or selected category changes.
  • Cleanup: Ignore outdated responses or cancel supported requests when they are no longer relevant.

Important: You do not need an Effect for every data-related task. If a request should happen because the user clicks a button or submits a form, it often belongs in that event handler. Framework data-loading features or libraries such as TanStack Query may be preferable for production applications.

4. Understanding the Data Fetching Process

  1. The React component renders.
  2. The Effect runs according to its dependency array.
  3. The browser sends a request to the API.
  4. The server returns a response.
  5. The application checks whether the request succeeded.
  6. The response body is converted into JavaScript data, often with response.json().
  7. The data is saved using a state setter such as setUsers().
  8. React renders the updated user interface.

Flow:

React Component
      |
      v
useEffect() Runs
      |
      v
Fetch API Request
      |
      v
Server Response
      |
      v
Check Response Status
      |
      v
Convert Response to JSON
      |
      v
Update React State
      |
      v
Render Data on Screen

5. Fetching Data Using fetch()

The browser's built-in fetch() function sends HTTP requests and returns a Promise. The response body can be read with methods such as response.json().

Basic example:

fetch("https://jsonplaceholder.typicode.com/users")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error("Request failed:", error));

This example retrieves a list of sample users and prints the response data in the browser console. In a React component, you can store the result in state and display it on the page.

6. Basic Example: Fetching Users in React

The following example retrieves users from a sample API and displays their names and email addresses.

import { useEffect, useState } from "react";

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

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

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

        const data = await response.json();
        setUsers(data);
      } catch (err) {
        setError(err.message || "Something went wrong");
      } finally {
        setLoading(false);
      }
    }

    fetchUsers();
  }, []);

  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 UserList;

Explanation:

  • useState([]) initializes the users list as an empty array.
  • useState(true) indicates that the request is initially loading.
  • useState("") stores an error message if the request fails.
  • useEffect() starts the request after the component commits.
  • fetch() sends a GET request to the sample API.
  • response.ok checks whether the HTTP response has a successful status.
  • response.json() parses the response body into JavaScript data.
  • setUsers(data) saves the fetched users in state.
  • finally ensures that the loading state is turned off whether the request succeeds or fails.
  • users.map() creates a list item for each user.
  • key={user.id} provides a stable key for each rendered item.

7. Understanding the Dependency Array

The dependency array controls when an Effect needs to run again. Every reactive value used by the Effect, including relevant props, state, and component-scope variables, must be included.

Dependency Behaviour Typical use
[] Runs after the initial commit, with an extra setup-and-cleanup cycle possible in development Strict Mode. Fetch initial data.
[userId] Runs initially and again when userId changes. Fetch a selected user's details.
[query, page] Runs initially and when either dependency changes. Fetch search results for a query and page.
No dependency array Runs after every commit. Usually avoid for data fetching because it may cause repeated requests.

Example:

useEffect(() => {
  fetchUser(userId);
}, [userId]);

When userId changes, the Effect runs again so the component can request the corresponding user's information. The example assumes fetchUser is defined appropriately and that its result is handled.

8. Handling Loading States

Network requests take time. A loading state tells users that the application is retrieving information instead of leaving them with a blank page.

const [loading, setLoading] = useState(true);

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

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

      const data = await response.json();
      setProducts(data);
    } catch (error) {
      setError(error.message);
    } finally {
      setLoading(false);
    }
  }

  loadData();
}, []);

In this snippet, products and setProducts should also be declared using useState(), and error and setError should be initialized as well.

Common loading indicators:

  • Loading text.
  • Spinner animation.
  • Skeleton placeholders.
  • Progress indicators for longer operations.

9. Handling API Errors

Errors can occur because of network problems, invalid URLs, server failures, authentication issues, or invalid response data.

Remember that fetch() generally does not reject its Promise just because the server returns an HTTP error status such as 404 or 500. Check response.ok and throw or handle an error when the response is unsuccessful.

try {
  const response = await fetch("/api/products");

  if (!response.ok) {
    throw new Error(`HTTP error: ${response.status}`);
  }

  const data = await response.json();
  setProducts(data);
} catch (error) {
  setError(error.message || "Unable to fetch products");
}

Good error-handling practices:

  • Display a clear, user-friendly error message.
  • Log useful debugging information during development.
  • Check the HTTP response status.
  • Handle invalid or unexpected response data when necessary.
  • Provide a retry option when appropriate.
  • Avoid exposing sensitive server details to end users.

10. Fetching Data with async/await

async/await makes Promise-based code easier to read. An Effect's callback itself should not be declared async, because an async function returns a Promise rather than the cleanup function React expects. Instead, define and call an async function inside the Effect.

useEffect(() => {
  async function getProducts() {
    try {
      const response = await fetch("/api/products");

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

      const data = await response.json();
      setProducts(data);
    } catch (error) {
      setError(error.message);
    }
  }

  getProducts();
}, []);

This snippet assumes products, setProducts, error, and setError are managed by state. For a complete implementation, include a loading state and cleanup logic where appropriate.

11. Cleanup Functions and Race Conditions

A race condition can happen when multiple requests are active and an older request finishes after a newer one. If the older response updates state last, the component may display outdated information.

For example, a user quickly selects different profiles. The request for the first profile may finish after the request for the second profile. Cleanup helps prevent a stale response from replacing the latest result.

Method 1: Ignore Outdated Responses

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

  async function loadUser() {
    try {
      const response = await fetch(`/api/users/${userId}`);

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

      const data = await response.json();

      if (!ignore) {
        setUser(data);
      }
    } catch (error) {
      if (!ignore) {
        setError(error.message);
      }
    }
  }

  loadUser();

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

When the Effect is cleaned up, its local ignore variable becomes true. The old request can finish, but its result will not update the component's state.

Method 2: Abort an In-Progress Request

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

  async function loadProducts() {
    try {
      const response = await fetch("/api/products", {
        signal: controller.signal
      });

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

      const data = await response.json();
      setProducts(data);
    } catch (error) {
      if (error.name !== "AbortError") {
        setError(error.message);
      }
    }
  }

  loadProducts();

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

AbortController can cancel a fetch request that supports its signal. The example assumes the relevant state setters are defined. In a real component, also manage loading and error states carefully so cleanup does not leave misleading UI behind.

12. Fetching Data When a Search Query Changes

Search pages commonly fetch new results when the search query changes. Include the query in the dependency array and protect against stale responses.

import { useEffect, useState } from "react";

function SearchUsers({ query }) {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

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

    async function search() {
      setLoading(true);
      setError("");

      try {
        const params = new URLSearchParams({ q: query });
        const response = await fetch(`/api/users?${params}`, {
          signal: controller.signal
        });

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

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

    search();

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

  if (loading) return <p>Searching...</p>;
  if (error) return <p>{error}</p>;

  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

export default SearchUsers;

This example assumes the API returns an array of users. In a production search interface, consider debouncing rapid input changes and defining what should happen when the query is empty.

13. Common Mistakes When Fetching Data

Mistake Why it is a problem Better approach
Forgetting to check response.ok HTTP errors may be treated like successful responses. Check the status before parsing the response.
Using an async Effect callback It returns a Promise rather than an optional cleanup function. Define an async function inside the Effect.
Missing dependencies The Effect may use outdated props or state. Include every reactive value used by the Effect.
No loading state Users cannot tell that data is being requested. Track loading and show a suitable indicator.
No error handling Failures can result in confusing or incomplete UI. Handle network, HTTP, and parsing errors.
No cleanup for changing requests Stale results may overwrite newer data. Abort requests or ignore outdated responses.
Fetching on every render Repeated requests can cause performance issues or loops. Specify the correct dependency array.
Using an Effect for every action It can make code unnecessarily complex. Use event handlers for actions triggered directly by user interactions.

14. Best Practices for Data Fetching

  • Use useEffect() when the request synchronizes the component with external data based on its current state or props.
  • Use useState() to manage fetched data, loading status, and errors.
  • Check response.ok before treating a response as successful.
  • Include all required reactive dependencies.
  • Use cleanup logic to cancel requests or ignore results that are no longer relevant.
  • Use stable identifiers such as user.id for list keys.
  • Avoid unnecessary requests and repeated state updates.
  • Keep API-related logic organized in reusable functions or custom Hooks when appropriate.
  • Do not store secrets or private API credentials in client-side code.
  • For larger applications, consider framework data loaders or libraries such as TanStack Query, SWR, or React Router data APIs for caching, request deduplication, and other optimizations.
  • Remember that Effects run only on the client and do not populate data during server rendering.
  • In development Strict Mode, expect an extra setup-and-cleanup cycle; write Effects that remain correct when this happens.

15. Practical Example: Product List

Objective: Retrieve products from an API and display their names and prices, with loading and error handling.

import { useEffect, useState } from "react";

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

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

    async function fetchProducts() {
      try {
        const response = await fetch(
          "https://dummyjson.com/products",
          { signal: controller.signal }
        );

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

        const result = await response.json();
        setProducts(result.products);
      } catch (error) {
        if (error.name !== "AbortError") {
          setError(error.message);
        }
      } finally {
        if (!controller.signal.aborted) {
          setLoading(false);
        }
      }
    }

    fetchProducts();

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

  if (loading) return <p>Loading products...</p>;
  if (error) return <p>Error: {error}</p>;

  return (
    <div>
      <h2>Products</h2>
      {products.map(product => (
        <div key={product.id}>
          <h3>{product.title}</h3>
          <p>Price: ${product.price}</p>
        </div>
      ))}
    </div>
  );
}

export default ProductList;

Expected result: The page initially shows a loading message. Once the request succeeds, it displays product titles and prices. If the request fails, it displays an error message. The cleanup function aborts the request if the Effect is cleaned up while the request is still in progress.

16. Frequently Asked Interview Questions

Q1. What is fetching data with Effects in React?

It is a technique for retrieving external data in an Effect and storing the result in state so React can display it.

Q2. Why do we use useEffect() for data fetching?

It lets a component synchronize with an external system when it appears or when relevant dependencies change.

Q3. What is the role of useState() in data fetching?

It stores fetched data and can also track loading status and error messages.

Q4. What does an empty dependency array mean?

It means the Effect has no reactive dependencies to watch, so it runs after the initial commit. Development Strict Mode may run an extra setup-and-cleanup cycle.

Q5. Why should we check response.ok?

Because fetch() normally resolves even for HTTP error statuses. Checking response.ok allows the application to handle unsuccessful responses explicitly.

Q6. Can an Effect callback be async?

It should not be declared async because an async callback returns a Promise. Define and call an async function inside the Effect instead.

Q7. What is a race condition in data fetching?

It occurs when requests finish in a different order than they were started, allowing an outdated response to overwrite newer data.

Q8. How can we prevent stale responses from updating state?

Use cleanup logic to ignore outdated results or use an AbortController to cancel supported fetch requests.

Q9. What is the purpose of a loading state?

It provides feedback while the application waits for the API response.

Q10. Is fetching data directly in Effects always the best approach?

No. Framework data-loading mechanisms and data-fetching libraries can provide caching, deduplication, server rendering support, and simpler request management.

17. Revision Checklist

  • Understand the purpose of useEffect().
  • Know how to send requests with fetch().
  • Understand how to parse JSON responses.
  • Store API data with useState().
  • Display loading and error states.
  • Check HTTP response status using response.ok.
  • Understand dependency arrays.
  • Use async functions inside Effects correctly.
  • Understand cleanup functions and race conditions.
  • Know when to consider a framework or data-fetching library.

18. Conclusion

Fetching data with Effects allows React components to request information from APIs and update their interfaces when that information becomes available. A reliable implementation handles loading, errors, HTTP status codes, dependencies, and cleanup. For complex applications, dedicated data-fetching tools may offer a more efficient and maintainable solution.

Learn more: Explore JustAcademy React JS Training | Register for a React JS Course Demo

Previous Next
whatsapp