Fetch Data with useEffect :👈 👉:Avoid Stale State React Hooks

How to Clean Up useEffect Correctly

How to Clean Up useEffect Correctly in React

1. What Is useEffect Cleanup?

In React, the cleanup function is a function returned by the callback passed to useEffect. It allows you to undo or release work performed by an effect when that work is no longer needed.

For example, a component might:

  • Register an event listener.
  • Start a timer or interval.
  • Open a WebSocket connection.
  • Subscribe to an external data source.
  • Start an API request that may become unnecessary.

When the effect is no longer needed, the cleanup function can remove the listener, stop the timer, close the connection, unsubscribe from the source, or cancel a supported request.

Simple rule: If an effect starts something that must later be stopped, disconnected, unsubscribed from, or cancelled, consider implementing a cleanup function.

2. Syntax of the useEffect Cleanup Function

import { useEffect } from "react";
useEffect(() => {
    // Set up an effect.
    return () => {
        // Clean up the effect.
    };
}, [dependencies]);

The effect contains two important parts:

  • Setup: Starts the operation or establishes the connection.
  • Cleanup: Reverses the setup or releases the resources that are no longer needed.

When Does Cleanup Run?

  1. Before the effect runs again: When a dependency changes, React runs the previous cleanup before setting up the new effect.
  2. When the component unmounts: React runs the cleanup for the effect.
  3. During development with Strict Mode: React performs an extra setup-and-cleanup cycle to help detect effects that are not correctly reversible.

Important: Cleanup is not limited to component unmounting. It also runs before React replaces an existing effect with a new one because its dependencies changed.

3. Example 1: Cleaning Up a Timer

Suppose a component starts an interval that updates a counter every second. If the interval is not cleared, it can continue running after the component is no longer displayed.

Incorrect Example

import { useEffect, useState } from "react";
function Timer() {
    const [seconds, setSeconds] = useState(0);
    useEffect(() => {
        setInterval(() => {
            setSeconds(previous => previous + 1);
        }, 1000);
    }, []);
    return <p>Seconds: {seconds}</p>;
}
export default Timer;

Problem: The interval ID is not stored, and the interval is never cleared. The timer can continue running after the component unmounts.

Correct Example

import { useEffect, useState } from "react";
function Timer() {
    const [seconds, setSeconds] = useState(0);
    useEffect(() => {
        const intervalId = setInterval(() => {
            setSeconds(previous => previous + 1);
        }, 1000);
        return () => {
            clearInterval(intervalId);
        };
    }, []);
    return <p>Seconds: {seconds}</p>;
}
export default Timer;

How It Works

  1. React runs the effect after the component commits its initial render.
  2. setInterval() starts the timer.
  3. The interval increments the state every second.
  4. When the component unmounts, React calls the cleanup function.
  5. clearInterval(intervalId) stops the timer.

Best practice: Use the functional state updater setSeconds(previous => previous + 1) when the next value depends on the previous value. This avoids relying on a potentially outdated value captured by the effect.

4. Example 2: Cleaning Up Event Listeners

Suppose you want to detect when the browser window is resized. You can register a resize event listener in an effect.

Incorrect Example

useEffect(() => {
    window.addEventListener("resize", handleResize);
}, []);

Problem: The listener is never removed. If the component is mounted and unmounted repeatedly, obsolete listeners may remain registered.

Correct Example

import { useEffect, useState } from "react";
function WindowWidth() {
    const [width, setWidth] = useState(window.innerWidth);
    useEffect(() => {
        function handleResize() {
            setWidth(window.innerWidth);
        }
        window.addEventListener("resize", handleResize);
        return () => {
            window.removeEventListener(
                "resize",
                handleResize
            );
        };
    }, []);
    return <p>Window width: {width}px</p>;
}
export default WindowWidth;

How It Works

  • The effect registers the event listener.
  • When the window is resized, handleResize updates the state.
  • The state update causes React to render the component again.
  • When the component unmounts, the cleanup removes the listener.

Important: This example assumes a browser-only application. In server-rendered applications, avoid accessing window during server rendering; initialize browser-dependent values in an appropriate client-side effect or use a suitable external-store abstraction.

Also, removeEventListener must receive the same event type, listener function, and relevant options used when registering the listener.

5. Example 3: Cleaning Up API Requests with AbortController

When fetching data, a request may become unnecessary because:

  • The component unmounts.
  • The user selects a different item.
  • The search term changes.
  • A newer request replaces the previous request.

AbortController lets you cancel a supported Fetch request.

Complete Example

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 fetchUser() {
            setLoading(true);
            setError("");
            try {
                const response = await fetch(
                    `https://jsonplaceholder.typicode.com/users/${userId}`,
                    {
                        signal: controller.signal
                    }
                );
                if (!response.ok) {
                    throw new Error(
                        `Request failed: ${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]);
    if (loading) {
        return <p>Loading user...</p>;
    }
    if (error) {
        return <p>Error: {error}</p>;
    }
    if (!user) {
        return <p>No user found.</p>;
    }
    return (
        <div>
            <h2>{user.name}</h2>
            <p>Email: {user.email}</p>
        </div>
    );
}
export default UserDetails;

How It Works

  1. The effect creates an AbortController.
  2. The request receives the controller's signal.
  3. If the component unmounts or userId changes, React runs the cleanup.
  4. The cleanup calls controller.abort().
  5. The cancelled request rejects, and the AbortError is ignored.
  6. The old request does not update the component with an obsolete result.

Important: Aborting Fetch cancels the supported client-side request operation. It does not guarantee that a server has stopped processing a request that it already received.

6. Example 4: Preventing Stale API Responses

Not every asynchronous operation supports cancellation. In such cases, an effect can use a cleanup flag to prevent an obsolete request from updating state.

import { useEffect, useState } from "react";
function UserDetails({ userId }) {
    const [user, setUser] = useState(null);
    const [error, setError] = useState("");
    useEffect(() => {
        let ignore = false;
        async function fetchUser() {
            try {
                const response = await fetch(
                    `https://jsonplaceholder.typicode.com/users/${userId}`
                );
                if (!response.ok) {
                    throw new Error("Failed to fetch user");
                }
                const data = await response.json();
                if (!ignore) {
                    setUser(data);
                    setError("");
                }
            } catch (err) {
                if (!ignore) {
                    setError(err.message);
                }
            }
        }
        fetchUser();
        return () => {
            ignore = true;
        };
    }, [userId]);
    if (error) {
        return <p>Error: {error}</p>;
    }
    if (!user) {
        return <p>Loading user...</p>;
    }
    return <h2>{user.name}</h2>;
}
export default UserDetails;

Why Does the Ignore Flag Work?

Each effect execution has its own ignore variable.

  1. The effect starts a request for the current userId.
  2. If userId changes, React runs the previous cleanup.
  3. The cleanup sets that effect's ignore variable to true.
  4. If the old request finishes later, it cannot update the component's state.

Difference from AbortController: The ignore flag prevents an obsolete result from being applied, but it does not cancel the network request. Use AbortController when supported cancellation is also desirable.

7. Example 5: Cleaning Up WebSocket Connections

WebSockets allow a client and server to exchange messages over a persistent connection. If a component opens a WebSocket, it should close the connection when it is no longer needed.

import { useEffect, useState } from "react";
function LiveUpdates() {
    const [messages, setMessages] = useState([]);
    useEffect(() => {
        const socket = new WebSocket(
            "wss://example.com/socket"
        );
        socket.addEventListener("message", event => {
            setMessages(previous => [
                ...previous,
                event.data
            ]);
        });
        return () => {
            socket.close();
        };
    }, []);
    return (
        <div>
            <h2>Live Updates</h2>
            <ul>
                {messages.map((message, index) => (
                    <li key={index}>{message}</li>
                ))}
            </ul>
        </div>
    );
}
export default LiveUpdates;

Note: Replace the example WebSocket URL with a real endpoint. Production applications may also need connection-state handling, reconnection logic, authentication, and message validation.

The cleanup closes the connection when the component unmounts. When an effect's dependencies change, the previous connection is cleaned up before a replacement is established.

8. Example 6: Cleaning Up a Debounce Timer

Suppose you want to perform an action only after a user stops typing for 500 milliseconds. You can use setTimeout() and clear the previous timeout when the input changes.

import { useEffect, useState } from "react";
function SearchBox() {
    const [searchTerm, setSearchTerm] = useState("");
    const [debouncedTerm, setDebouncedTerm] = useState("");
    useEffect(() => {
        const timeoutId = setTimeout(() => {
            setDebouncedTerm(searchTerm);
        }, 500);
        return () => {
            clearTimeout(timeoutId);
        };
    }, [searchTerm]);
    useEffect(() => {
        if (!debouncedTerm.trim()) {
            return;
        }
        console.log("Search for:", debouncedTerm);
        // Perform the search using debouncedTerm.
    }, [debouncedTerm]);
    return (
        <div>
            <input
                value={searchTerm}
                onChange={event =>
                    setSearchTerm(event.target.value)
                }
                placeholder="Search..."
            />
            <p>Search term: {debouncedTerm}</p>
        </div>
    );
}
export default SearchBox;

How It Works

  1. The user types a character, updating searchTerm.
  2. The effect starts a timeout for 500 milliseconds.
  3. If the user types again before the timeout finishes, React runs the previous cleanup.
  4. clearTimeout() cancels the previous timeout.
  5. When the user stops typing for 500 milliseconds, the latest search term becomes debouncedTerm.

This reduces unnecessary work. If the second effect makes API requests, you should also consider request cancellation or stale-result protection.

9. Understanding React Strict Mode and useEffect Cleanup

When React Strict Mode is enabled in development, React performs an additional effect setup-and-cleanup cycle to help reveal incorrect effect behavior.

For example, consider this effect:

useEffect(() => {
    console.log("Effect started");
    return () => {
        console.log("Effect cleaned up");
    };
}, []);

In development with Strict Mode enabled, you may see this sequence during the initial mount:

Effect started
Effect cleaned up
Effect started

This is intentional development behavior. It helps reveal effects that assume setup happens only once or that fail to release resources correctly.

In production, React does not perform this additional Strict Mode development check.

How Should You Handle It?

  • Make setup and cleanup correctly mirror one another.
  • Remove event listeners that were added.
  • Clear timers that were started.
  • Close connections that were opened.
  • Cancel obsolete requests or prevent obsolete results from being applied.
  • Do not disable Strict Mode simply to hide duplicate development logs or requests.

Important: Some operations, such as sending a payment or creating a record, should not be triggered by a mount effect merely because a component appeared. Initiate user-triggered actions from their event handlers and make server-side operations appropriately safe against retries and duplicate submissions.

10. Common useEffect Cleanup Mistakes

Mistake 1: Forgetting to Return a Cleanup Function

If an effect registers a listener or starts an interval but does not clean it up, the resource can continue running longer than intended.

Incorrect:

useEffect(() => {
    const id = setInterval(doSomething, 1000);
}, []);

Correct:

useEffect(() => {
    const id = setInterval(doSomething, 1000);
    return () => {
        clearInterval(id);
    };
}, []);

Mistake 2: Returning the Wrong Value

The effect callback must return either nothing or a cleanup function. Do not return a Promise or another arbitrary value.

Incorrect:

useEffect(() => {
    return fetch("/api/users");
}, []);

Correct:

useEffect(() => {
    const controller = new AbortController();
    fetch("/api/users", {
        signal: controller.signal
    }).catch(error => {
        if (error.name !== "AbortError") {
            console.error(error);
        }
    });
    return () => {
        controller.abort();
    };
}, []);

This example demonstrates the cleanup pattern. In a complete application, also handle HTTP status codes and display loading and error states as appropriate.

Mistake 3: Using a Different Function to Remove an Event Listener

Incorrect:

useEffect(() => {
    window.addEventListener("resize", () => {
        console.log("Resized");
    });
    return () => {
        window.removeEventListener("resize", () => {
            console.log("Resized");
        });
    };
}, []);

The two arrow functions are different function objects, so the listener is not removed.

Correct:

useEffect(() => {
    function handleResize() {
        console.log("Resized");
    }
    window.addEventListener("resize", handleResize);
    return () => {
        window.removeEventListener(
            "resize",
            handleResize
        );
    };
}, []);

Mistake 4: Ignoring Dependencies

If an effect uses a changing value but omits it from the dependency array, the effect may continue using an outdated value.

Include the reactive values used by the effect in its dependency array, or restructure the effect so it no longer needs to depend on a value unnecessarily.

Mistake 5: Using Cleanup to Reset Every State Variable

Cleanup is primarily for reversing effect setup and preventing obsolete work. It is not necessary to reset every state variable when a component unmounts.

When a component unmounts, its local state is no longer retained by that component instance. Focus cleanup on resources, subscriptions, and asynchronous work that require it.

11. When Is Cleanup Necessary?

Operation Is Cleanup Needed? Typical Cleanup
setInterval() Yes clearInterval()
setTimeout() When the timeout may become obsolete clearTimeout()
Event listener Yes, when the listener is no longer needed removeEventListener()
WebSocket Yes, when the connection is no longer needed close()
External subscription Yes Unsubscribe
Fetch request Often, if the request becomes obsolete AbortController.abort() or stale-result protection
Simple calculation inside an effect Usually not No cleanup needed if no external resource or ongoing work is created

12. Best Practices for useEffect Cleanup

  • Mirror setup with cleanup: If setup registers a listener, cleanup should remove it. If setup opens a connection, cleanup should close it.
  • Keep cleanup specific: Clean up the exact resource created by that effect execution.
  • Handle dependency changes: Remember that cleanup runs before an effect is re-established with new dependencies.
  • Use AbortController for Fetch: Cancel requests when they are no longer needed and the operation supports cancellation.
  • Prevent stale results: Use an ignore flag, request identifier, or another suitable strategy when cancellation is unavailable or insufficient.
  • Keep event handler references stable within the effect: Use the same function reference for registration and removal.
  • Follow the Rules of Hooks: Call useEffect at the top level of React components or custom Hooks.
  • Respect Strict Mode: Make effects resilient to the extra development setup-and-cleanup cycle.
  • Avoid unnecessary effects: If a value can be calculated directly during rendering from existing props or state, an effect may not be necessary.
  • Test cleanup: Verify that listeners, timers, connections, and obsolete requests are handled correctly.

13. Interview Questions and Answers

Q1. What is the cleanup function in useEffect?

It is the function returned by the effect callback. React calls it before re-running that effect and when the component unmounts, allowing resources to be released or obsolete work to be stopped.

Q2. When does useEffect cleanup run?

Cleanup runs before an effect is re-executed because its dependencies changed and when the component unmounts. In development, Strict Mode also performs an additional setup-and-cleanup cycle.

Q3. Why should we clear timers?

Clearing timers prevents callbacks from continuing after they are no longer needed. This avoids unnecessary work and prevents obsolete timer callbacks from affecting application behavior.

Q4. How do you cancel a Fetch request in useEffect?

Create an AbortController, pass its signal to fetch(), and call controller.abort() in the cleanup function. Handle the resulting abort error appropriately.

Q5. What is the difference between AbortController and an ignore flag?

AbortController requests cancellation of a supported operation. An ignore flag prevents a result from updating state after it becomes obsolete, but it does not cancel the underlying operation.

Q6. Why does Strict Mode run cleanup immediately after setup in development?

React uses this extra cycle to help reveal effects that cannot be safely set up, cleaned up, and set up again.

Q7. Does every useEffect need cleanup?

No. Cleanup is necessary when the effect establishes a resource or starts work that must be reversed, released, or prevented from applying obsolete results. A simple effect without ongoing resources may not need cleanup.

14. Summary

Concept Purpose
Effect setup Starts an operation or synchronizes with an external system.
Cleanup function Reverses setup or releases resources when they are no longer needed.
clearInterval() Stops an interval.
clearTimeout() Cancels a pending timeout.
removeEventListener() Removes a registered event listener.
AbortController Cancels supported Fetch requests.
Ignore flag Prevents obsolete asynchronous results from updating state.
Strict Mode Helps detect effects that do not clean up correctly.

Final takeaway: Correct useEffect cleanup prevents obsolete resources and operations from continuing after they are no longer needed. Whenever an effect creates a timer, registers a listener, opens a connection, or starts a request that may become obsolete, determine how to clean it up. This makes React components more reliable and easier to maintain.

🔙
Fetch Data with useEffect :👈 👉:Avoid Stale State React Hooks

Comments and Discussion