Custom Hooks in React :👈 👉:useEffect Clean Up Correctly

How to Fetch Data with useEffect

How to Fetch Data with useEffect in React

1. What Is useEffect?

useEffect is a React Hook used to synchronize a component with external systems, such as APIs, browser events, timers, and subscriptions.

One common use is fetching data from an API after a component renders.

For example, a React application might need to:

  • Fetch a list of users from an API.
  • Display product information from a server.
  • Load customer details when a page opens.
  • Fetch new data when a user selects a different category.
  • Display loading indicators and error messages while fetching data.

Basic idea: Use useEffect to start the request, useState to store the response, and JSX to display the result.

2. Basic Syntax of useEffect

import { useEffect } from "react";
useEffect(() => {
    // Perform an effect.
    return () => {
        // Optional cleanup.
    };
}, [dependencies]);

The three important parts are:

  • Effect function: Contains the operation that should run after React commits a render.
  • Cleanup function: Optionally cleans up resources or cancels work before the effect runs again or the component unmounts.
  • Dependency array: Determines when React needs to run the effect again.

Understanding the Dependency Array

Syntax Behavior
useEffect(() => {}) Runs after every commit. Without a dependency array, an effect that updates state may create an infinite render loop.
useEffect(() => {}, []) Runs after the initial mount in production, with cleanup when the component unmounts. React Strict Mode may perform an additional development-only setup and cleanup cycle.
useEffect(() => {}, [userId]) Runs after the initial mount and again when userId changes.

React compares dependency values using Object.is. Include every reactive value used by the effect in its dependency array unless a specific React-supported pattern removes that dependency.

3. Example 1: Fetch Data from an API

Let's fetch a list of users from a sample API and display their names.

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

Complete React Example

import { useEffect, useState } from "react";
function Users() {
    const [users, setUsers] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    useEffect(() => {
        async function fetchUsers() {
            try {
                const response = await fetch(
                    "https://jsonplaceholder.typicode.com/users"
                );
                if (!response.ok) {
                    throw new Error(
                        `HTTP error: ${response.status}`
                    );
                }
                const data = await response.json();
                setUsers(data);
            } catch (err) {
                setError(err.message);
            } finally {
                setLoading(false);
            }
        }
        fetchUsers();
    }, []);
    if (loading) {
        return <p>Loading users...</p>;
    }
    if (error) {
        return <p>Error: {error}</p>;
    }
    return (
        <div>
            <h2>Users List</h2>
            <ul>
                {users.map(user => (
                    <li key={user.id}>
                        {user.name} - {user.email}
                    </li>
                ))}
            </ul>
        </div>
    );
}
export default Users;

How It Works

  1. useState([]) initializes the users list as an empty array.
  2. useState(true) indicates that the request is initially loading.
  3. useEffect starts the API request after the component's initial render.
  4. fetch() sends an HTTP request to the API endpoint.
  5. response.ok checks whether the HTTP response indicates success.
  6. response.json() parses the response body as JSON.
  7. setUsers(data) stores the returned users and schedules a re-render.
  8. The catch block handles errors, and finally ends the loading state.
  9. The component displays the loading message, error message, or users list depending on the current state.

Important: The Fetch API does not automatically throw an error for HTTP responses such as 404 or 500. Checking response.ok allows you to handle unsuccessful HTTP responses explicitly.

4. Why Should You Not Make the useEffect Callback async?

An async function always returns a Promise. However, React expects the effect callback to return either nothing or a cleanup function, not a Promise.

Incorrect:

useEffect(async () => {
    const response = await fetch("/api/users");
    const data = await response.json();
    setUsers(data);
}, []);

Correct:

useEffect(() => {
    async function fetchUsers() {
        const response = await fetch("/api/users");
        if (!response.ok) {
            throw new Error("Failed to fetch users");
        }
        const data = await response.json();
        setUsers(data);
    }
    fetchUsers().catch(error => {
        console.error(error);
    });
}, []);

The effect callback remains synchronous, while the inner function handles the asynchronous operation.

In a complete component, you should also store the error in state, display an appropriate error message, and clean up or ignore obsolete requests when necessary.

5. Example 2: Fetch Data with Loading and Error Handling

In real applications, API requests can fail because of network problems, server errors, invalid endpoints, or authorization issues.

A robust component should manage three states:

  • Loading: The request is in progress.
  • Success: The data has been received.
  • Error: The request failed.

Complete Example

import { useEffect, useState } from "react";
function Products() {
    const [products, setProducts] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState("");
    useEffect(() => {
        let ignore = false;
        async function fetchProducts() {
            setLoading(true);
            setError("");
            try {
                const response = await fetch(
                    "https://fakestoreapi.com/products"
                );
                if (!response.ok) {
                    throw new Error(
                        `Request failed: ${response.status}`
                    );
                }
                const data = await response.json();
                if (!ignore) {
                    setProducts(data);
                }
            } catch (err) {
                if (!ignore) {
                    setError(err.message);
                }
            } finally {
                if (!ignore) {
                    setLoading(false);
                }
            }
        }
        fetchProducts();
        return () => {
            ignore = true;
        };
    }, []);
    if (loading) {
        return <p>Loading products...</p>;
    }
    if (error) {
        return <p>Unable to load products: {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 Products;

Why Is the ignore Variable Used?

The ignore variable prevents an obsolete effect instance from updating component state after its cleanup has run.

For example, if a component unmounts while the request is still pending, the cleanup sets ignore to true. When the request finishes, its result is not applied.

This pattern helps avoid stale updates, but it does not cancel the network request itself. Use AbortController when you also want to cancel a supported Fetch request.

6. Example 3: Fetch Data When a Dependency Changes

Sometimes an API request depends on a value selected by the user. For example, selecting a different user should fetch that user's details.

In this case, include the relevant identifier in the dependency array.

Complete Example

import { useEffect, useState } from "react";
function UserDetails() {
    const [userId, setUserId] = useState(1);
    const [user, setUser] = useState(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState("");
    useEffect(() => {
        const controller = new AbortController();
        async function fetchUser() {
            setLoading(true);
            setError("");
            setUser(null);
            try {
                const response = await fetch(
                    `https://jsonplaceholder.typicode.com/users/${userId}`,
                    { signal: controller.signal }
                );
                if (!response.ok) {
                    throw new Error(
                        `Failed to fetch user: ${response.status}`
                    );
                }
                const data = await response.json();
                setUser(data);
            } catch (err) {
                if (err.name !== "AbortError") {
                    setError(err.message);
                }
            } finally {
                if (!controller.signal.aborted) {
                    setLoading(false);
                }
            }
        }
        fetchUser();
        return () => {
            controller.abort();
        };
    }, [userId]);
    return (
        <div>
            <h2>User Details</h2>
            <button onClick={() => setUserId(1)}>
                User 1
            </button>
            <button onClick={() => setUserId(2)}>
                User 2
            </button>
            <button onClick={() => setUserId(3)}>
                User 3
            </button>
            {loading && <p>Loading user...</p>}
            {error && <p>Error: {error}</p>}
            {user && (
                <div>
                    <p>Name: {user.name}</p>
                    <p>Email: {user.email}</p>
                    <p>City: {user.address.city}</p>
                </div>
            )}
        </div>
    );
}
export default UserDetails;

How It Works

  1. The initial userId is 1.
  2. The effect fetches the details for user 1.
  3. When you click the User 2 button, setUserId(2) updates the state.
  4. React renders the component with the new identifier.
  5. The effect cleanup aborts the previous request when possible, and the effect starts a request for user 2.
  6. The component displays the new user's details when the request succeeds.

Key point: The dependency array [userId] tells React that the effect must re-run when the selected user changes.

7. Understanding Race Conditions in API Requests

A race condition can occur when multiple requests are running at the same time and their responses arrive in a different order from the order in which the requests were started.

For example:

  1. The user selects User 1, starting request A.
  2. Before request A finishes, the user selects User 2, starting request B.
  3. Request B finishes first and displays User 2.
  4. Request A finishes later and overwrites the UI with User 1.

The UI now displays outdated data even though User 2 is selected.

How to Prevent Race Conditions

Two common approaches are:

  • AbortController: Cancel an obsolete Fetch request when the effect is cleaned up.
  • Ignore flag or request identifier: Prevent an outdated request from updating state after a newer request has taken over.

The previous UserDetails example uses AbortController. This works well with Fetch, but cancellation alone is not a universal solution for every asynchronous operation. For operations that cannot be cancelled, use an explicit mechanism to ignore obsolete results.

Example Using an Ignore Flag

useEffect(() => {
    let ignore = false;
    async function fetchData() {
        try {
            const response = await fetch(url);
            if (!response.ok) {
                throw new Error("Request failed");
            }
            const result = await response.json();
            if (!ignore) {
                setData(result);
            }
        } catch (err) {
            if (!ignore) {
                setError(err.message);
            }
        }
    }
    fetchData();
    return () => {
        ignore = true;
    };
}, [url]);

Here, url represents a reactive value declared in the component. Include it in the dependency array so the effect re-runs when the URL changes.

8. Example 4: Fetch Data When a Search Term Changes

Consider a search box that fetches users based on a search term. The effect should run when the search term changes.

import { useEffect, useState } from "react";
function UserSearch() {
    const [searchTerm, setSearchTerm] = useState("");
    const [users, setUsers] = useState([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState("");
    useEffect(() => {
        if (!searchTerm.trim()) {
            setUsers([]);
            setLoading(false);
            setError("");
            return;
        }
        const controller = new AbortController();
        async function searchUsers() {
            setLoading(true);
            setError("");
            try {
                const response = await fetch(
                    `https://jsonplaceholder.typicode.com/users?username=${encodeURIComponent(searchTerm)}`,
                    { signal: controller.signal }
                );
                if (!response.ok) {
                    throw new Error("Search request failed");
                }
                const data = await response.json();
                setUsers(data);
            } catch (err) {
                if (err.name !== "AbortError") {
                    setError(err.message);
                }
            } finally {
                if (!controller.signal.aborted) {
                    setLoading(false);
                }
            }
        }
        searchUsers();
        return () => {
            controller.abort();
        };
    }, [searchTerm]);
    return (
        <div>
            <h2>Search Users</h2>
            <input
                type="text"
                value={searchTerm}
                onChange={event =>
                    setSearchTerm(event.target.value)
                }
                placeholder="Search by username"
            />
            {loading && <p>Searching...</p>}
            {error && <p>Error: {error}</p>}
            {!loading && !error && users.length === 0 && searchTerm.trim() !== "" && (
                <p>No users found.</p>
            )}
            <ul>
                {users.map(user => (
                    <li key={user.id}>
                        {user.name} ({user.username})
                    </li>
                ))}
            </ul>
        </div>
    );
}
export default UserSearch;

Note: This example demonstrates dependency-based fetching, but it sends a request whenever the search term changes. In a real search interface, you may want to debounce input to avoid unnecessary requests while the user is typing.

9. Common Mistakes When Fetching Data with useEffect

Mistake 1: Forgetting the Dependency Array

Incorrect:

useEffect(() => {
    fetchData();
});

This effect runs after every commit. If fetchData() updates state, the component may render again and trigger another request repeatedly.

Correct when fetching only for the initial mount:

useEffect(() => {
    fetchData();
}, []);

For a real implementation, define the asynchronous function inside the effect or use a stable function reference with the correct dependencies. Use an appropriate cleanup strategy when needed.

Mistake 2: Using an Empty Dependency Array When a Value Changes

If the request depends on userId, an empty dependency array means the effect will not automatically fetch data for later identifier changes.

Correct:

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

The function in this simplified example represents your fetching logic. Make sure all reactive values used by the effect are accounted for.

Mistake 3: Forgetting to Check response.ok

The Fetch API can resolve successfully at the network level even when the server returns an HTTP error status such as 404 or 500.

Correct:

const response = await fetch(url);
if (!response.ok) {
    throw new Error(`HTTP error: ${response.status}`);
}
const data = await response.json();

Mistake 4: Not Handling Errors

Without error handling, failed requests can leave the UI stuck in a loading state or produce unhandled Promise rejections.

Use try...catch...finally to manage the request lifecycle, and display meaningful error feedback to users.

Mistake 5: Ignoring Cleanup

When an effect starts a request, changes subscriptions, or creates a timer, determine whether cleanup is necessary. For Fetch requests, AbortController is useful when the request becomes obsolete.

Mistake 6: Assuming useEffect Runs Only Once in Development

When React Strict Mode is enabled, React performs an additional development-only effect setup and cleanup cycle to help reveal unsafe side effects. Your fetching logic should tolerate cleanup and repeated setup rather than relying on an effect running exactly once.

10. When Should You Use useEffect for Data Fetching?

Using useEffect with Fetch is useful when a component needs to synchronize with an external API in response to mounting or changes in reactive values.

However, fetching data directly in effects has limitations:

  • It does not automatically cache responses.
  • It does not automatically deduplicate identical requests.
  • You must manage loading and error states yourself.
  • You must consider cancellation and race conditions.
  • It can lead to network waterfalls when components fetch sequentially.
  • Server rendering does not automatically execute client-side effects to load the initial page data.

For larger applications, consider a data-fetching library such as TanStack Query or SWR, or use your framework's recommended data-loading approach. These solutions can provide caching, request deduplication, refetching, and other features.

11. Best Practices

  • Use useEffect to synchronize with external systems, not merely to derive one state value from another.
  • Use useState to store API data, loading status, and errors when those values determine the UI.
  • Never make the effect callback itself async.
  • Check response.ok before parsing a response that is expected to indicate success.
  • Include the correct dependencies in the dependency array.
  • Use AbortController or another suitable cleanup strategy when requests become obsolete.
  • Prevent stale responses from overwriting newer results.
  • Show appropriate loading, empty, success, and error states.
  • Use stable keys when rendering lists of API results.
  • For complex data requirements, consider a dedicated data-fetching library or framework-level solution.

12. Interview Questions and Answers

Q1. Why do we use useEffect for fetching data?

useEffect allows a component to synchronize with an external system, such as an API, after React commits a render. It can start a request on mount or when relevant dependencies change.

Q2. Why should the useEffect callback not be async?

An async function returns a Promise. React expects an effect callback to return either nothing or a cleanup function, so the asynchronous work should be placed inside a separate async function.

Q3. What is the purpose of the dependency array?

The dependency array specifies the reactive values that determine when an effect must run again. React compares the dependencies with their previous values using Object.is.

Q4. What is the purpose of AbortController?

AbortController allows supported asynchronous operations, including Fetch requests, to be cancelled. It is useful when a request becomes obsolete because a dependency changes or a component no longer needs the result.

Q5. What is a race condition in API fetching?

A race condition occurs when overlapping requests finish in an unexpected order, allowing an older response to overwrite a newer result. Cancellation or explicit stale-result handling can prevent this.

Q6. Why must we check response.ok?

Fetch does not automatically reject its Promise for HTTP error responses such as 404 and 500. Checking response.ok lets the application handle those responses as errors.

Q7. Does useEffect run twice in React Strict Mode?

In development, React Strict Mode performs an additional effect setup and cleanup cycle to help identify unsafe side effects. This behavior does not mean production effects are always executed twice.

Q8. Is useEffect always the best way to fetch data?

No. It works for many straightforward cases, but larger applications may benefit from a data-fetching library or framework-level loading approach that handles caching, deduplication, and other concerns.

13. Summary

Concept Purpose
useEffect Starts and manages synchronization with external systems.
useState Stores response data, loading status, and error information.
fetch() Sends the HTTP request.
response.ok Checks whether the HTTP response has a successful status.
response.json() Parses a JSON response body.
Dependency array Determines which reactive value changes cause the effect to run again.
AbortController Cancels supported requests when they are no longer needed.
Cleanup function Releases resources and prevents obsolete work from affecting the component.

Final takeaway: To fetch data with useEffect, create an effect, perform the asynchronous request inside a separate function, store the result with useState, and handle loading and errors. Include the correct dependencies and use cleanup or stale-result protection when requests may overlap or become obsolete.

🔙
Custom Hooks in React :👈 👉:useEffect Clean Up Correctly

Comments and Discussion