AI Hints
Home›React Tutorial›Fetching Data
React · Lesson 41 of 120

Race Conditions

Ignore old results.

⏱ 2 min read▶ Video at 32:39🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

When the effect depends on something the user changes, requests can finish out of order. A slow old answer might arrive after the new one, and overwrite it. That's a race condition.

  • User changes the input
  • Requests overlap
  • Old answer wins

Ignoring stale results

The effect loads one product, whenever the id changes. It sets an ignore flag to false. The cleanup sets it to true, so an old request's result is thrown away. We click quickly through two products. Run it. Only the latest product is shown.

App.jsxjsx
import { useState, useEffect } from "react";
import { getProduct } from "./api";
export default function App() {
  const [id, setId] = useState(1);
  const [product, setProduct] = useState(null);
  useEffect(() => {
    let ignore = false;
    getProduct(id).then(p => {
      if (!ignore) setProduct(p);
      else console.log("ignored old result for", p.name);
    });
    return () => { ignore = true; };
  }, [id]);
  return (
    <div><p className="box">{product ? product.name : "Loading..."}</p>
      {[1, 2, 3].map(n => <button key={n} id={"b" + n} onClick={() => setId(n)}>Product {n}</button>)}</div>
  );
}
Output
ignored old result for City 200
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}
Also uses api.js
const PRODUCTS = [
  { id: 1, name: "Trail 500", price: 849.5, type: "bike", stock: 12 },
  { id: 2, name: "City 200", price: 450, type: "bike", stock: 0 },
  { id: 3, name: "Volt 7", price: 2199, type: "bike", stock: 4 },
  { id: 4, name: "Helmet", price: 40, type: "gear", stock: 30 },
  { id: 5, name: "Lights", price: 25, type: "gear", stock: 18 },
];
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

export async function getProducts() {
  await wait(300);
  return PRODUCTS;
}

export async function getProduct(id) {
  await wait(300);
  const product = PRODUCTS.find(p => p.id === Number(id));
  if (!product) throw new Error(`Product ${id} not found`);
  return product;
}
Also uses actions.json
[{"wait": 500}, {"click": "#b2"}, {"click": "#b3"}, {"wait": 600}]

In real apps

The ignore flag is the simplest fix. Real apps often use a data library, like TanStack Query, which handles caching, retries, and races for you. It's still good to understand what's happening underneath.

keyvalue
Simple fixignore flag
LibrariesTanStack Query
They addcaching, retries
Knowthe basics

Summary

Use an ignore flag in the cleanup, so old requests can't overwrite new results. Next, when you don't need an effect.

Key takeaways
  • let ignore
  • Cleanup sets it
  • Latest wins
Next up: You Might Not Need an Effect — simpler code