Course contentsShow
← React
Lesson 578 of 2,39616. useEffect for Data FetchingFree lesson

What Race Conditions Are in Data Fetching

Understanding how multiple async requests can complete out of order and cause stale data bugs in your UI.

What Race Conditions Are in Data Fetching

You'll learn: How multiple async requests can finish in unpredictable order and display wrong data in your UI.

The Core Problem

A race condition in data fetching occurs when you trigger multiple async requests (like fetches), but they complete in a different order than they were sent. The slower request might finish after a faster one, overwriting your UI with stale data.

Imagine searching for a city's weather. You type "Boston" (request #1 starts), then quickly change it to "Berlin" (request #2 starts). If the Boston request is slower and finishes after Berlin's response arrives, your UI will show Boston's weather even though "Berlin" is selected. The requests "raced" each other, and the wrong one won.

Why This Happens in React

When a prop or state changes (like a search term or user ID), your useEffect runs again and starts a new fetch. But the old fetch doesn't automatically stop. Both requests are now "in flight" simultaneously, and JavaScript makes no guarantees about which will complete first—network speed, server load, and timing all vary.

// Dangerous pattern:
useEffect(() => {
  fetch(`/api/user/${userId}`)
    .then(res => res.json())
    .then(data => setUser(data)); // Sets whoever finishes last!
}, [userId]);

If userId changes from 5 to 6 quickly, both fetches run. If user #5's response arrives after user #6's, you'll display user #5's data while thinking you're showing user #6.

The Analogy

Think of ordering food delivery from two restaurants simultaneously, then canceling the first order. If the first delivery still shows up and you eat it by mistake, you've experienced a race condition.

Key Takeaway: Race conditions happen when multiple async fetches overlap and the last one to finish isn't necessarily the one you wanted, causing your UI to display stale or incorrect data.