- Published on
Avoiding Race Conditions in useEffect! ๐ข
- Authors

- Name
- Mamun Rashid
Ever had a dinner guest who couldn't make up their mind about what to order? First they ask for pasta, then they change their mind and want pizza. So now we're cooking both meals at once. Uh-oh. If the pasta finishes first, we might serve it by mistake, even though the guest really wanted pizza.
The same mess can happen with useEffect in React if we're not careful. Misusing useEffect can lead to race conditions: earlier actions (like data fetching) finish after newer ones, and the app ends up with outdated or wrong information.
It's a common problem. We'll look at how it happens and a few scenarios to avoid, then use React's clean-up function to prevent it.
The Single, Indecisive Guest: How Race Conditions Happen in React ๐ฏ
We have one guest at our dinner party. They ask for pasta, and we start cooking. Halfway through, they change their mind and ask for pizza instead. Now two meals are cooking at the same time. If the pasta finishes first, we serve it to the guest by mistake, even though they really wanted the pizza.
In React, this plays out when a state update kicks off several asynchronous tasks (like API requests) through useEffect. If we don't handle it, earlier requests can finish after newer ones, and the app shows old or incorrect information.
The Messy Kitchen: Race Conditions in Code ๐
Here's how it looks in code:
import { useEffect, useState } from 'react';
function MealOrderComponent({ currentOrder }) {
const [meal, setMeal] = useState(null);
const [isCooking, setIsCooking] = useState(false);
useEffect(() => {
const prepareMeal = async (mealId) => {
setIsCooking(true);
await sleep(Math.random() * 3000); // Meal prep takes a random time
setMeal(mealId); // Serve meal to guest
setIsCooking(false);
};
prepareMeal(currentOrder);
}, [currentOrder]);
return <div>{isCooking ? 'Cooking...' : `Served: ${meal}`}</div>;
}
currentOrder is the meal the guest wants, pasta or pizza. prepareMeal simulates cooking it, and it takes a random amount of time to finish. setMeal(mealId) is the moment we serve the meal to the guest.
Without some care, we might serve the pasta (the earlier request) even though the guest switched to pizza (the latest request).
That's a classic race condition. Both requests are racing to finish, and the last one to complete wins, whether or not it's the right one.
Chaos in the Kitchen: How Do We Fix It? ๐งโ๐ณ
We need a way to cancel the pasta order when the guest changes their mind. Picture a "sticky note" in the kitchen. Whenever the guest updates their order, we leave a note saying, "Cancel the pasta if it finishes after the pizza starts cooking!"
The Hero: Clean-Up Function to Save the Day ๐
React lets us clean up or cancel tasks inside useEffect with a clean-up function. Here's our code with one in place, so we always serve the most recent meal:
useEffect(() => {
let cancelPreviousMeal = false; // The sticky note: "Cancel the earlier meal"
const prepareMeal = async (mealId) => {
setIsCooking(true);
await sleep(Math.random() * 3000); // Random meal prep time
if (!cancelPreviousMeal) {
// Only serve if no cancellation happened
setMeal(mealId); // Serve the correct meal
}
setIsCooking(false); // Always reset cooking state
};
prepareMeal(currentOrder);
return () => {
cancelPreviousMeal = true; // Cancel the earlier meal when the new one starts
};
}, [currentOrder]);
We keep setIsCooking(false) outside the condition so it always runs. That way the UI doesn't get stuck in a "cooking" state when a result is ignored.
Why This Works: The Sticky Note System ๐๐ฝ๏ธ
cancelPreviousMeal is our sticky note. It tracks whether an old meal should be ignored. Every time the guest changes their order (when currentOrder updates), the sticky note goes on the earlier meal, so it gets dropped if it finishes after the new one starts. With the clean-up function in place, we only serve the most recent meal, which is pizza in this case.
Real-World Example: Data Fetching ๐
Data fetching is where race conditions show up most often. Say we're building a user profile viewer that loads different user data as the user navigates:
import { useEffect, useState } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
let ignore = false; // Flag to ignore stale requests
const fetchUser = async () => {
setLoading(true);
setError(null);
try {
const response = await fetch(`/api/users/${userId}`);
const data = await response.json();
if (!ignore) {
// Only update if this is still the current request
setUser(data);
}
} catch (err) {
if (!ignore) {
setError(err.message);
}
} finally {
if (!ignore) {
setLoading(false);
}
}
};
fetchUser();
return () => {
ignore = true; // Mark this request as stale when userId changes
};
}, [userId]);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
return <div>User: {user?.name}</div>;
}
If userId changes from 1 to 2 to 3 quickly, three fetch requests start. Network delays mean the request for user 1 might finish last. Without the ignore flag we'd show user 1's data even though we want user 3. The cleanup function sets ignore = true, so the stale data never gets displayed.
Modern Approach: Using AbortController ๐
For fetch requests, the modern and recommended approach is AbortController. It cancels the network request itself instead of ignoring the result:
useEffect(() => {
const controller = new AbortController();
const signal = controller.signal;
const fetchUser = async () => {
setLoading(true);
setError(null);
try {
const response = await fetch(`/api/users/${userId}`, { signal });
const data = await response.json();
setUser(data);
} catch (err) {
// Ignore abort errors
if (err.name !== 'AbortError') {
setError(err.message);
}
} finally {
setLoading(false);
}
};
fetchUser();
return () => {
controller.abort(); // Actually cancel the fetch request
};
}, [userId]);
Why reach for AbortController? It cancels the network request, which saves bandwidth. It's a browser-native API, so there are no extra dependencies. Passing a signal around is cleaner syntax. A cancelled request throws AbortError automatically. And every modern browser supports it (Chrome 66+, Firefox 57+, Safari 12.1+).
TypeScript Version
For better type safety, here's the TypeScript version:
import { useEffect, useState } from 'react';
interface User {
id: number;
name: string;
email: string;
}
function UserProfile({ userId }: { userId: number }) {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const controller = new AbortController();
const fetchUser = async () => {
setLoading(true);
setError(null);
try {
const response = await fetch(`/api/users/${userId}`, {
signal: controller.signal,
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data: User = await response.json();
setUser(data);
} catch (err) {
if (err instanceof Error && err.name !== 'AbortError') {
setError(err.message);
}
} finally {
setLoading(false);
}
};
fetchUser();
return () => {
controller.abort();
};
}, [userId]);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
return <div>User: {user?.name}</div>;
}
React 18+ Strict Mode Considerations โ๏ธ
In React 18+, Strict Mode intentionally double-invokes effects in development to help you find bugs. Your effect runs once, its cleanup runs, and then the effect runs again.
That extra cycle is on purpose. It's how Strict Mode catches missing cleanup logic. If you see double requests in development, that's normal. In production, effects only run once.
Best Practices Summary ๐
- Always use cleanup functions for async operations in useEffect.
- Prefer AbortController for fetch requests. It's modern and efficient.
- Use boolean flags (
ignoreorcancelled) for other async tasks. - Handle errors properly, which means ignoring
AbortErrorfrom cancelled requests. - Test in Strict Mode, since it helps catch missing cleanup logic.
- Consider a custom hook so the pattern is reusable.
Wrapping It Up: Keep the Kitchen and Code Clean! ๐งน
Async work in React, like fetching data or handling user actions, can easily race if we don't manage requests properly. A clean-up function in useEffect stops old tasks from interfering with new ones, so only the most recent action takes effect.
Modern tools like AbortController make this easier still, because they cancel the network request instead of ignoring its result. React 18's Strict Mode then catches the bugs we miss, early.
A well-run kitchen cancels old orders and serves the right meal. Do the same in your effects and the app won't serve up outdated data.
Enjoyed this post?
Subscribe to get notified about new posts and updates. No spam, unsubscribe anytime.
By subscribing, you agree to our Privacy Policy. You can unsubscribe at any time.
Discussion
Loading comments...
This website is still under development. If you encounter any issues, please contact me.
Found this useful? Support the blog