| Infinite-API-Requests-in-React :👈 | 👉:Memory Leaks in React |
How to Fix Race Conditions in React API Calls |
How to Fix Race Conditions in React API Calls
1. Quick Answer
A race condition in React API calls occurs when multiple asynchronous requests are running at the same time and their responses arrive in an unexpected order. An older response may overwrite newer data, causing the UI to display incorrect or outdated information.
Common solutions:
- Use
AbortControllerto cancel obsolete fetch requests. - Use an effect cleanup flag to prevent outdated responses from updating state.
- Use a request ID or sequence number to accept only the latest request's result.
- Handle loading and error states carefully when multiple requests overlap.
- Use a data-fetching library when caching, request deduplication, and request lifecycle management are needed.
2. Table of Contents
- What Is a Race Condition?
- Real-World Example
- How a Race Condition Happens
- Incorrect React Code
- Solution 1: Using AbortController
- Solution 2: Using an Effect Cleanup Flag
- Solution 3: Using Request IDs
- Complete Example: Search Users
- Handling Loading and Error States
- Race Conditions and React Strict Mode
- Common Mistakes
- Best Practices
- React Interview Questions
- Summary
3. What Is a Race Condition?
A race condition occurs when the correctness of a result depends on the order in which concurrent operations finish.
In React, API requests are asynchronous. If a user triggers multiple requests, the requests may complete in a different order from the order in which they started.
For example:
- A user searches for React.
- Before the first request finishes, the user searches for Angular.
- The Angular request finishes first and displays Angular results.
- The older React request finishes later and replaces the Angular results.
The UI now displays results for the wrong search term. This is a race condition.
Why Does It Happen?
- Network latency varies between requests.
- Some API operations take longer than others.
- Users can trigger multiple requests quickly.
- Components may render with new props or state while earlier requests remain active.
- Older responses may update state after newer requests have completed.
4. Real-World Example
Consider an e-commerce application with a product search box.
| Time | User Action or API Event | Result |
|---|---|---|
| 0 ms | User searches for Laptop. | Request A starts. |
| 100 ms | User changes the search to Mobile. | Request B starts. |
| 300 ms | Request B completes. | Mobile results are displayed. |
| 900 ms | Request A completes. | Laptop results overwrite Mobile results. |
Expected behavior: The UI should continue displaying Mobile results because Mobile is the user's latest search.
Actual problem: The older Laptop request finishes later and overwrites the newer results.
5. How a Race Condition Happens
The solution is to ensure that an obsolete request cannot overwrite the result of a newer request.
6. Incorrect React Code
The following example fetches users whenever the search query changes, but it does not prevent an older request from updating the state.
import { useEffect, useState } from "react";
function SearchUsers({ query }) {
const [users, setUsers] = useState([]);
useEffect(() => {
async function fetchUsers() {
const response = await fetch(
"/api/users?q=" + encodeURIComponent(query)
);
const data = await response.json();
setUsers(data);
}
fetchUsers();
}, [query]);
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
export default SearchUsers;
Problem: The dependency array correctly causes the effect to run when query changes. However, requests from earlier effect executions may still finish later and update users.
Important: Correct dependencies prevent one class of bugs, such as stale effect dependencies. They do not automatically prevent out-of-order API responses.
7. Solution 1: Using AbortController
AbortController allows you to cancel a fetch request when it is no longer needed. When the query changes, the effect cleanup aborts the previous request before the new effect starts its own request.
Correct Code
import { useEffect, useState } from "react";
function SearchUsers({ query }) {
const [users, setUsers] = useState([]);
const [error, setError] = useState("");
useEffect(() => {
if (!query.trim()) {
setUsers([]);
setError("");
return;
}
const controller = new AbortController();
async function fetchUsers() {
try {
const response = await fetch(
"/api/users?q=" + encodeURIComponent(query),
{ signal: controller.signal }
);
if (!response.ok) {
throw new Error("Failed to fetch users");
}
const data = await response.json();
setUsers(data);
setError("");
} catch (err) {
if (err.name !== "AbortError") {
setError(err.message);
}
}
}
fetchUsers();
return () => {
controller.abort();
};
}, [query]);
return (
<div>
{error && <p>{error}</p>}
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
export default SearchUsers;
How It Works
- A new controller is created for each effect execution.
- The request receives the controller's abort signal.
- When the query changes, React runs the previous effect's cleanup.
- The cleanup calls
controller.abort(). - The obsolete fetch is cancelled where possible, and its abort error is not displayed as an ordinary API error.
Advantages:
- Prevents unnecessary client-side work when requests are no longer needed.
- Reduces the likelihood of obsolete responses updating the UI.
- Works naturally with effects that fetch data based on changing props or state.
Limitation: Cancellation is not a universal guarantee that an operation has stopped on the server. Also, if an API client does not support abort signals, you need another strategy to prevent obsolete results from updating state.
8. Solution 2: Using an Effect Cleanup Flag
A cleanup flag prevents an earlier effect execution from updating state after it has become obsolete.
Correct Code
import { useEffect, useState } from "react";
function SearchUsers({ query }) {
const [users, setUsers] = useState([]);
useEffect(() => {
let ignore = false;
async function fetchUsers() {
try {
const response = await fetch(
"/api/users?q=" + encodeURIComponent(query)
);
if (!response.ok) {
throw new Error("Failed to fetch users");
}
const data = await response.json();
if (!ignore) {
setUsers(data);
}
} catch (err) {
if (!ignore) {
console.error(err);
}
}
}
fetchUsers();
return () => {
ignore = true;
};
}, [query]);
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
export default SearchUsers;
How It Works
- Each effect execution has its own
ignorevariable. - When the query changes or the component unmounts, cleanup sets that execution's flag to
true. - If its request completes afterward, it cannot update the users state.
- The current effect execution can still update state normally.
Advantages:
- Simple to implement.
- Prevents obsolete results from updating state.
- Does not require the API client to support cancellation.
Limitation: The request still runs unless the underlying operation is cancelled separately. The flag prevents the result from being used; it does not stop network activity.
9. Solution 3: Using Request IDs
A request ID or sequence number can ensure that only the latest request is allowed to update the state. This is useful when requests are initiated by multiple event handlers or through logic outside a single effect.
Example
import { useRef, useState } from "react";
function SearchUsers() {
const [query, setQuery] = useState("");
const [users, setUsers] = useState([]);
const requestIdRef = useRef(0);
async function handleSearch() {
const currentRequestId = ++requestIdRef.current;
const currentQuery = query;
if (!currentQuery.trim()) {
setUsers([]);
return;
}
try {
const response = await fetch(
"/api/users?q=" + encodeURIComponent(currentQuery)
);
if (!response.ok) {
throw new Error("Failed to fetch users");
}
const data = await response.json();
if (currentRequestId === requestIdRef.current) {
setUsers(data);
}
} catch (err) {
if (currentRequestId === requestIdRef.current) {
console.error(err);
}
}
}
return (
<div>
<input
value={query}
onChange={event => setQuery(event.target.value)}
placeholder="Search users"
/>
<button onClick={handleSearch}>Search</button>
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
export default SearchUsers;
How It Works
- Each search increments the request sequence number.
- The request records the sequence number that belongs to it.
- When a response arrives, its sequence number is compared with the latest number.
- Only the request with the current number can update the users state.
Important limitation: This example handles searches initiated by clicking the Search button. If the query changes, but no new search is submitted, the latest request ID does not change. If the desired behavior is to invalidate previous requests immediately when the input changes, increment or invalidate the request ID in the input-change logic, or use an effect tied to the query.
Request IDs also do not cancel network requests. They control which results are accepted.
10. Complete Example: Search Users
The following example combines a query-dependent effect, request cancellation, loading state, and error handling. It ensures that an obsolete request does not replace the results for the latest query.
import { useEffect, useState } from "react";
function SearchUsers() {
const [query, setQuery] = useState("");
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
useEffect(() => {
if (!query.trim()) {
setUsers([]);
setLoading(false);
setError("");
return;
}
const controller = new AbortController();
async function searchUsers() {
setLoading(true);
setError("");
try {
const response = await fetch(
"/api/users?q=" + encodeURIComponent(query),
{ 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();
};
}, [query]);
return (
<div>
<h2>Search Users</h2>
<input
value={query}
onChange={event => setQuery(event.target.value)}
placeholder="Enter a name"
/>
{loading && <p>Loading users...</p>}
{error && <p>Error: {error}</p>}
{!loading && !error && users.length === 0 && query.trim() !== "" && (
<p>No users found.</p>
)}
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
export default SearchUsers;
Note: This example sends a request whenever the query changes. For a real search box, consider debouncing the query so that a request is not sent for every keystroke. The loading indicator is also simplified: if the query changes rapidly, the previous effect's cleanup and the new effect's setup can overlap briefly. For more complex request flows, use a request ID or a data-fetching library to coordinate loading state and result updates explicitly.
11. Handling Loading and Error States
Race conditions can affect more than the data displayed in the UI. They can also cause incorrect loading indicators and error messages.
Example of a Loading-State Problem
async function fetchData() {
setLoading(true);
try {
const response = await fetch("/api/data");
const data = await response.json();
setData(data);
} finally {
setLoading(false);
}
}
If two requests run simultaneously, the first request may finish while the second is still running. The first request sets loading to false, even though the second request remains active.
For latest-request-wins behavior, coordinate the loading state with the same request ID used to protect the data.
const requestIdRef = useRef(0);
async function fetchData() {
const requestId = ++requestIdRef.current;
setLoading(true);
try {
const response = await fetch("/api/data");
if (!response.ok) {
throw new Error("Request failed");
}
const data = await response.json();
if (requestId === requestIdRef.current) {
setData(data);
setError("");
}
} catch (err) {
if (requestId === requestIdRef.current) {
setError(err.message);
}
} finally {
if (requestId === requestIdRef.current) {
setLoading(false);
}
}
}
This pattern ensures that only the latest request controls the data, error, and loading state. In a real component, define the state and ref with the appropriate React hooks and invalidate the request ID when the component's current request context becomes obsolete.
12. Race Conditions and React Strict Mode
React Strict Mode may run effect setup and cleanup an additional time during development to help detect unsafe effects. This can make an API request appear to run twice during the initial mount.
This is not necessarily a race condition or an infinite loop.
| Situation | Possible Explanation |
|---|---|
| Two initial requests in development | Strict Mode may be checking effect setup and cleanup behavior. |
| Old results overwrite new results | Requests are completing out of order without stale-result protection. |
| Requests continue after changing the query | Older requests may not be cancelled, or their results may not be ignored. |
| Loading stops while another request is running | One request is changing shared loading state without checking whether it is still current. |
Best practice: Make effects safe to repeat, implement cleanup, and ensure that obsolete requests cannot update the current UI. Do not disable Strict Mode merely to hide duplicate requests.
13. Common Mistakes
| Mistake | Why It Is a Problem | Better Approach |
|---|---|---|
| Assuming responses arrive in request order | Network latency can cause responses to arrive in any order. | Use cancellation, cleanup flags, or request IDs. |
| Using correct dependencies but no stale-result protection | Correct dependencies do not prevent an older response from finishing last. | Protect state updates from obsolete requests. |
| Using AbortController without handling abort errors | Expected cancellations may be treated as ordinary errors. | Handle AbortError separately. |
| Using a cleanup flag but expecting it to cancel a request | The flag prevents state updates but does not stop the network operation. | Use AbortController when supported and appropriate. |
| Protecting data but not loading state | An old request can incorrectly change the loading indicator. | Apply the same request-validity check to data, error, and loading updates. |
| Incrementing a request ID only when submitting a search | Changing the input without submitting may leave the old request considered current. | Invalidate the request when the relevant query context changes. |
| Assuming cancellation stops server-side work | The server may already be processing the request. | Implement appropriate server-side cancellation or idempotency when required. |
| Ignoring errors from obsolete requests | Old failures may display errors that no longer relate to the current query. | Only let the current request update the error state. |
14. Best Practices
- Choose an explicit policy: Decide whether the application should accept every response or only the latest request's result.
- Use AbortController: Cancel obsolete fetch requests when they are no longer needed.
- Use cleanup flags when appropriate: Prevent obsolete asynchronous work from updating state.
- Use request IDs for overlapping operations: Accept results only when the request remains current.
- Protect every related state update: Apply request-validity checks to data, loading, and error states.
- Debounce search input: Reduce unnecessary requests when users type quickly.
- Use caching and deduplication: A library such as TanStack Query can help coordinate requests, cache results, and manage query lifecycles.
- Keep dependency arrays correct: Include reactive values that the effect uses.
- Handle errors explicitly: Distinguish request failures from intentional cancellations.
- Test slow responses: Simulate different response times to verify that outdated results cannot replace current data.
15. React Interview Questions
Q1. What is a race condition in React API calls?
It occurs when multiple asynchronous requests overlap and the order in which they complete affects the result. An older response can overwrite newer data if the application does not protect its state updates.
Q2. Why do API responses arrive out of order?
Different requests can experience different network delays, server processing times, and response sizes. The order in which requests start does not guarantee the order in which they finish.
Q3. How does AbortController help?
It allows a fetch request to be aborted when the request is no longer needed. It is commonly used in effect cleanup when a dependency changes or a component unmounts.
Q4. What is the difference between cancellation and ignoring a response?
Cancellation attempts to stop the underlying operation. Ignoring a response allows the operation to finish but prevents its result from updating the current UI state.
Q5. When should you use request IDs?
Request IDs are useful when multiple requests can overlap and only the most recent request should update the state. They are particularly helpful for requests initiated by event handlers or more complex workflows.
Q6. Does useEffect dependency management solve race conditions?
No. Correct dependencies determine when an effect should rerun, but they do not guarantee that overlapping requests finish in order. Stale-result protection is still needed when response order matters.
Q7. How can race conditions affect loading indicators?
An earlier request may finish and set loading to false while a later request is still running. Associate loading updates with the current request or use a request-management solution that coordinates overlapping operations.
Q8. Can React Strict Mode cause race conditions?
Strict Mode helps expose effects that are not safe to repeat. It may make duplicate requests visible during development, but out-of-order results need their own handling.
Q9. How do you prevent race conditions in search autocomplete?
Debounce input where appropriate, cancel obsolete requests, and ensure that only results for the current query can update the UI.
Q10. How can TanStack Query help?
TanStack Query provides query caching, request lifecycle management, and mechanisms for coordinating data fetching. Correct query keys and cancellation behavior are still important when inputs change or requests overlap.
16. Summary
- A race condition occurs when overlapping API requests finish in an unexpected order.
- An older response may overwrite newer data if every response is allowed to update state.
- Use
AbortControllerto cancel obsolete fetch requests where possible. - Use an effect cleanup flag to ignore results from obsolete effect executions.
- Use request IDs when only the latest request should update the UI.
- Protect loading and error states as well as the returned data.
- Use debouncing, caching, and request deduplication where appropriate.
- Keep effect dependencies correct and make effects safe to repeat.
Golden Rule: When multiple API requests can overlap, explicitly decide which responses are allowed to update the UI. For latest-request-wins behavior, cancel obsolete requests where possible and ensure that only the current request can update data, loading, and error state.
| Infinite-API-Requests-in-React :👈 | 👉:Memory Leaks in React |
Comments and Discussion