Race Conditions in React API Calls :👈 👉:Input-Field-Not-Updating

How to Fix Memory Leaks in React Applications

How to Fix Memory Leaks in React Applications

1. Quick Answer

A memory leak in a React application occurs when memory or resources are retained longer than necessary, even though the application no longer needs them. This can increase memory consumption, degrade performance, and make the application slower over time.

Common causes include:

  • Intervals and timeouts that are not cleared.
  • Event listeners that are not removed.
  • Subscriptions that are not cancelled.
  • WebSocket connections that remain open unnecessarily.
  • Asynchronous operations that retain references or continue doing unnecessary work.
  • Large objects or DOM elements retained by references.

Common solutions:

  • Return cleanup functions from useEffect.
  • Clear timers using clearInterval() and clearTimeout().
  • Remove event listeners using removeEventListener().
  • Unsubscribe from subscriptions and close connections when they are no longer needed.
  • Abort unnecessary fetch requests using AbortController.
  • Use browser developer tools to identify objects that remain in memory unexpectedly.

2. Table of Contents

3. What Is a Memory Leak?

A memory leak occurs when a program retains memory that it no longer needs and that cannot be reclaimed by the garbage collector.

JavaScript automatically manages memory using garbage collection. However, memory cannot be reclaimed while objects remain reachable through references, active timers, event listeners, subscriptions, or other retained objects.

React applications can experience memory leaks when components create resources but fail to release them when those resources are no longer needed.

Example

Imagine a component starts an interval when it mounts but never clears it when it unmounts. The interval can continue running and retaining references to its callback and related objects.

If the user opens and closes the component repeatedly, multiple intervals may remain active unnecessarily.

Potential consequences include:

  • Increasing memory consumption.
  • Unnecessary background processing.
  • Duplicate event handling.
  • Unexpected updates or callbacks.
  • Slowdowns in long-running applications.

Important distinction: An asynchronous request completing after a component unmounts is not automatically a memory leak. A leak involves resources or objects being retained unnecessarily. However, uncleaned asynchronous work can waste resources and may expose lifecycle bugs.

4. Common Causes of Memory Leaks

Cause Problem Solution
setInterval The interval continues running after the component no longer needs it. Call clearInterval().
setTimeout A pending timeout may execute after it is no longer needed. Call clearTimeout() when appropriate.
Event listeners Listeners remain registered and may retain callback references. Remove them using removeEventListener().
Subscriptions External services continue sending events to an inactive component. Unsubscribe during cleanup.
WebSocket connections Connections remain open unnecessarily. Close the connection when it is no longer required.
API requests Unnecessary requests continue consuming network and processing resources. Abort obsolete fetch requests when possible.
Global references Large objects remain reachable through global variables or long-lived stores. Release references when they are no longer needed.
Detached DOM elements JavaScript references keep removed DOM elements and their associated data alive. Remove unnecessary references and listeners.
Unbounded caches Cached data accumulates without an eviction strategy. Limit cache size or implement expiration and eviction.

5. How a Memory Leak Happens

Missing Cleanup → Potential Memory Leak Component Mounts Resource Created Timer / Listener / Subscription Starts Component Unmounts Cleanup Function Missing Timer / Listener Continues Running References Cannot Be Garbage Collected Memory Usage or Background Work Increases Potential Memory Leak

The correct lifecycle is:

Proper Resource Cleanup Lifecycle Component Mounts Resource Created Component Uses Resource Component Unmounts or Dependency Changes Cleanup Runs Resource Released Resource Can Be Garbage Collected No Memory Leak

6. Example 1: Fixing an Interval Memory Leak

Incorrect Code

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

Problem: The interval is created when the effect runs, but its ID is not stored and no cleanup function clears it.

If the component unmounts, the interval can continue running and retaining its callback.

Correct Code

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

Why This Works

  • The effect creates the interval.
  • The interval updates the counter every second.
  • The cleanup function clears the interval when the component unmounts.
  • If the effect needs to rerun because its dependencies change, React cleans up the previous interval before setting up the next one.

Key point: Always clear intervals created by an effect when the effect no longer needs them.

7. Example 2: Fixing a Timeout

A timeout can also remain pending after the component no longer needs its callback to execute.

Incorrect Code

import { useEffect, useState } from "react";
function Notification() {
    const [message, setMessage] = useState("Saving...");
    useEffect(() => {
        setTimeout(() => {
            setMessage("Saved successfully");
        }, 5000);
    }, []);
    return <p>{message}</p>;
}
export default Notification;

Problem: The timeout is not cleared if the component unmounts before five seconds have elapsed.

Correct Code

import { useEffect, useState } from "react";
function Notification() {
    const [message, setMessage] = useState("Saving...");
    useEffect(() => {
        const timeoutId = setTimeout(() => {
            setMessage("Saved successfully");
        }, 5000);
        return () => {
            clearTimeout(timeoutId);
        };
    }, []);
    return <p>{message}</p>;
}
export default Notification;

Why this works: The cleanup function cancels the pending timeout when the component unmounts or the effect is replaced.

Note: A pending timeout is not automatically a significant memory leak. Cleanup is useful when the callback should no longer run or when it retains resources unnecessarily.

8. Example 3: Removing Event Listeners

Global event listeners registered on objects such as window or document can remain active after a component unmounts.

Incorrect Code

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

Problem: The resize listener is never removed. The anonymous callback also cannot be directly passed to removeEventListener() later unless its reference is retained.

Correct Code

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 <h2>Width: {width}px</h2>;
}
export default WindowWidth;

Why This Works

  • The event handler is stored in a named function.
  • The effect registers the handler.
  • The cleanup function removes the same function reference.
  • The browser no longer retains that listener through the registration after cleanup.

Important: The same event type, listener function reference, and relevant listener options must match when removing a listener.

9. Example 4: Cleaning Up API Requests

API requests do not automatically cause memory leaks, but obsolete requests can continue consuming resources. If a component no longer needs the result, it can abort the fetch where supported.

Example Using AbortController

import { useEffect, useState } from "react";
function UserProfile({ userId }) {
    const [user, setUser] = useState(null);
    const [error, setError] = useState("");
    useEffect(() => {
        const controller = new AbortController();
        async function fetchUser() {
            try {
                const response = await fetch(
                    "/api/users/" + userId,
                    { signal: controller.signal }
                );
                if (!response.ok) {
                    throw new Error("Failed to fetch user");
                }
                const data = await response.json();
                setUser(data);
                setError("");
            } catch (err) {
                if (err.name !== "AbortError") {
                    setError(err.message);
                }
            }
        }
        fetchUser();
        return () => {
            controller.abort();
        };
    }, [userId]);
    if (error) {
        return <p>Error: {error}</p>;
    }
    if (!user) {
        return <p>Loading user...</p>;
    }
    return <h2>{user.name}</h2>;
}
export default UserProfile;

Why This Works

  • The effect fetches the user associated with userId.
  • When userId changes or the component unmounts, cleanup aborts the previous fetch.
  • Intentional cancellation is handled separately from other errors.
  • Obsolete requests are less likely to waste resources or produce outdated results.

Important: Aborting a fetch does not guarantee that the server has stopped processing the request. Also, a fetch request completing after unmount is not automatically a memory leak. Cleanup is useful when the operation is no longer needed.

10. Example 5: Cleaning Up Subscriptions

Applications may subscribe to external data sources, event emitters, or observable streams. These subscriptions should be released when the component no longer needs updates.

Incorrect Code

import { useEffect, useState } from "react";
function MessageCounter({ messageService }) {
    const [count, setCount] = useState(0);
    useEffect(() => {
        messageService.subscribe(() => {
            setCount(previous => previous + 1);
        });
    }, [messageService]);
    return <h2>Messages: {count}</h2>;
}

Problem: The example does not unsubscribe. If the component unmounts or the service changes, the previous subscription may continue invoking its callback.

Correct Code

import { useEffect, useState } from "react";
function MessageCounter({ messageService }) {
    const [count, setCount] = useState(0);
    useEffect(() => {
        const unsubscribe = messageService.subscribe(() => {
            setCount(previous => previous + 1);
        });
        return () => {
            unsubscribe();
        };
    }, [messageService]);
    return <h2>Messages: {count}</h2>;
}
export default MessageCounter;

Assumption: This example assumes that messageService.subscribe() returns an unsubscribe function. Actual subscription APIs differ, so use the cleanup method provided by the service.

Why This Works

  • The component subscribes when the effect runs.
  • The returned unsubscribe function is stored.
  • The cleanup function releases the subscription.
  • React runs cleanup before setting up the effect again when messageService changes, and when the component unmounts.

11. Example 6: Cleaning Up WebSocket Connections

A WebSocket can remain connected and continue receiving messages even when the component that opened it is no longer displayed.

Correct Code

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

Why this works:

  • The effect opens a WebSocket connection.
  • The component listens for incoming messages.
  • The cleanup function removes the message listener and closes the connection.
  • The connection is released when the component unmounts.

Production consideration: If messages have stable IDs, use those IDs as React keys instead of array indexes. If a connection is shared by multiple components, manage it in a shared service rather than closing it whenever any individual component unmounts.

12. Example 7: Avoiding Unnecessary References

JavaScript's garbage collector can reclaim objects only when they are no longer reachable. A global variable, long-lived cache, or persistent callback can accidentally retain a large object graph.

Problematic Example

const cachedResponses = [];
function cacheResponse(response) {
    cachedResponses.push(response);
}

Problem: The array grows without a limit. If the responses contain large objects, the application may use increasing amounts of memory.

Improved Example: Keep Only a Limited Number of Entries

const cachedResponses = [];
const MAX_CACHE_SIZE = 100;
function cacheResponse(response) {
    cachedResponses.push(response);
    if (cachedResponses.length > MAX_CACHE_SIZE) {
        cachedResponses.shift();
    }
}

This example limits the number of retained entries, although a production cache may need a more appropriate eviction strategy based on size, access patterns, and expiration.

In React applications:

  • Avoid storing unnecessary copies of large API responses.
  • Remove obsolete entries from caches.
  • Release references when data is no longer required.
  • Avoid keeping DOM elements in long-lived collections without a clear reason.
  • Use virtualization for very large rendered lists when appropriate.

Do not manually clear every reference without understanding its purpose. Garbage collection works automatically when objects are no longer reachable.

13. Understanding React Strict Mode

React Strict Mode can run an effect's setup, cleanup, and setup again during development to help identify effects that do not clean up correctly.

For example, an effect that creates an interval without clearing it may accidentally leave multiple intervals running during development checks.

Situation Possible Explanation
An effect runs twice during initial development rendering Strict Mode may be checking whether setup and cleanup are correct.
Several intervals continue running The interval cleanup may be missing or incorrect.
Event handlers fire multiple times Duplicate listeners or subscriptions may have been registered.
Memory increases each time a component opens Resources may not be released when the component unmounts.

Best practice: Do not disable Strict Mode simply to hide repeated effect execution. Make the effect safe to set up and clean up more than once.

14. How to Debug Memory Leaks in React

Step 1: Reproduce the Problem

Repeat the action that appears to increase memory usage. For example, navigate to a page, open a modal, start a timer, and then leave the page. Repeat the sequence several times.

Step 2: Inspect the Browser's Memory Tools

In Chrome or Edge, open Developer Tools and inspect the Memory panel. Depending on the browser version, you can use heap snapshots, allocation sampling, or allocation timelines to investigate memory usage.

Step 3: Take Heap Snapshots

Take a snapshot before and after repeating the action. Compare the snapshots to identify objects that remain in memory unexpectedly.

Step 4: Check Retained Objects

Look for retained event listeners, detached DOM nodes, large arrays, cached API responses, and objects that remain reachable through unexpected references.

Step 5: Inspect Effect Cleanup

Review every effect that creates a resource:

  • Does each setInterval() have a corresponding clearInterval()?
  • Does each setTimeout() have a corresponding clearTimeout() when needed?
  • Are event listeners removed with the correct function reference?
  • Are subscriptions unsubscribed?
  • Are WebSocket connections closed when appropriate?
  • Are obsolete fetch requests cancelled where possible?

Step 6: Repeat the Test

After fixing the suspected problem, repeat the same interaction and compare memory behavior. A memory increase during normal activity is not sufficient evidence of a leak; look for objects that remain retained unnecessarily or memory usage that grows without stabilizing.

15. Common Mistakes

Mistake Why It Is a Problem Better Approach
Creating an interval without cleanup The interval may continue running after the component unmounts. Store the timer ID and clear the interval.
Registering listeners without removing them Listeners can retain callbacks and trigger unnecessary work. Remove listeners during cleanup.
Assuming React automatically clears external resources React cannot automatically clean up every timer, connection, or subscription created by application code. Return an appropriate cleanup function from the effect.
Treating every post-unmount response as a memory leak An asynchronous response completing after unmount does not automatically indicate retained memory. Investigate actual resource retention and cancel unnecessary work.
Using anonymous event handlers without retaining their references The same handler reference is needed for ordinary listener removal. Use a named function or retain the callback reference.
Keeping an unlimited cache Cached objects can accumulate indefinitely. Set cache limits, expiration, or an eviction policy.
Disabling Strict Mode This can hide lifecycle problems rather than fix them. Make effects safe to set up and clean up repeatedly.
Clearing resources that are intentionally shared A component may accidentally disconnect resources still needed elsewhere. Manage shared resources at the appropriate ownership level.

16. Best Practices

  • Clean up effects: Return a cleanup function whenever an effect creates resources that need releasing.
  • Clear timers: Use clearInterval() and clearTimeout() when those timers are no longer needed.
  • Remove event listeners: Retain the handler reference so it can be removed correctly.
  • Unsubscribe from external services: Release subscriptions when their owning component no longer needs them.
  • Close connections: Close WebSockets and similar connections at the appropriate lifecycle boundary.
  • Cancel obsolete requests: Use AbortController where supported and appropriate.
  • Limit cached data: Avoid unbounded collections and caches.
  • Use stable effect dependencies: Prevent unnecessary resource creation and cleanup cycles.
  • Test repeated mounting and unmounting: Verify that resources do not accumulate over time.
  • Measure before optimizing: Use heap snapshots and allocation tools to confirm whether a real memory leak exists.

17. React Interview Questions

Q1. What is a memory leak in React?

A memory leak occurs when objects or resources remain retained after the application no longer needs them, preventing their memory from being reclaimed or causing unnecessary background work.

Q2. What are common causes of memory leaks in React?

Common causes include uncleared timers, unremoved event listeners, subscriptions that are not released, open connections, unbounded caches, and unintended references to large objects.

Q3. How does useEffect cleanup help?

The cleanup function releases resources created by an effect when the component unmounts or before the effect runs again because its dependencies changed.

Q4. How do you prevent interval memory leaks?

Store the interval ID and call clearInterval() in the effect's cleanup function.

Q5. How do you prevent event-listener memory leaks?

Register the listener in an effect and remove the same listener during cleanup using removeEventListener().

Q6. Is an API response arriving after unmount a memory leak?

Not necessarily. It may be an unnecessary asynchronous operation, but a memory leak requires unnecessary memory retention. Abort obsolete requests when appropriate and ensure that obsolete results cannot update the current UI.

Q7. What is the purpose of AbortController?

AbortController can cancel supported operations, including fetch requests, when they are no longer needed. It helps reduce unnecessary client-side work but does not guarantee that server-side processing stops.

Q8. How can you identify memory leaks in a React application?

Use browser developer tools to inspect heap snapshots, memory allocation, retained objects, and detached DOM nodes. Repeat the suspected action and compare memory behavior.

Q9. Why can Strict Mode expose memory leaks?

Strict Mode can run effect setup and cleanup again during development, helping reveal effects that fail to release resources or are not safe to repeat.

Q10. Does useRef cause memory leaks?

No. Using useRef is not inherently a memory leak. However, a ref can retain an object for as long as the component and the reference remain reachable. Clear or replace the reference when retaining that object is no longer necessary.

18. Summary

  • A memory leak occurs when memory or resources remain retained longer than necessary.
  • React applications can leak resources when timers, listeners, subscriptions, or connections are not cleaned up.
  • Use effect cleanup to release resources at the appropriate lifecycle boundary.
  • Clear intervals and timeouts when they are no longer needed.
  • Remove event listeners and unsubscribe from external services.
  • Abort obsolete fetch requests when appropriate.
  • Limit caches and release unnecessary references.
  • Use browser memory tools to confirm suspected leaks instead of relying only on memory usage at one moment.
  • Make effects safe to set up and clean up repeatedly, including under React Strict Mode.

Golden Rule: Whenever a React effect creates an external resource, such as a timer, event listener, subscription, or connection, define how that resource will be released when the effect is no longer needed.

🔙
Race Conditions in React API Calls :👈 👉:Input-Field-Not-Updating

Comments and Discussion