Race Conditions & Cleanup

0/3 in this phase0/36 across the roadmap

📖 Concept

A Race Condition in React happens when multiple async requests are made, and they resolve in a different order than they were sent.

The Problem: User clicks "Category A", then quickly clicks "Category B". If the request for A takes 5 seconds but B takes 1 second, the results for B will show first, then be overwritten by the "older" results for A. The UI is now showing the wrong data!

The Solutions:

  1. Boolean Flag: Use a variable to track if the current effect is still valid.
  2. AbortController: Built-in browser API to actually cancel the network request. This is the preferred modern way.

💻 Code Example

codeTap to expand ⛶
1import React, { useState, useEffect } from 'react';
2
3function ProductDetails({ productId }) {
4 const [product, setProduct] = useState(null);
5
6 useEffect(() => {
7 // 1. Create the controller
8 const controller = new AbortController();
9 const signal = controller.signal;
10
11 const fetchProduct = async () => {
12 try {
13 const res = await fetch(`https://api.example.com/products/${productId}`, { signal });
14 const data = await res.json();
15 setProduct(data);
16 } catch (err) {
17 if (err.name === 'AbortError') {
18 console.log('Fetch aborted: The component updated before I finished.');
19 } else {
20 console.error('Real error:', err);
21 }
22 }
23 };
24
25 fetchProduct();
26
27 // 2. CLEANUP: Abort the fetch if productId changes or component unmounts
28 return () => {
29 controller.abort();
30 };
31 }, [productId]);
32
33 if (!product) return <div>Loading...</div>;
34 return <h1>{product.name}</h1>;
35}

🏋️ Practice Exercise

  1. Simulate a slow network in Chrome DevTools and build a component that switches between different data tabs. Observe race conditions without cleanup.
  2. Implement the 'Boolean Flag' approach to solving race conditions.
  3. Build a 'Typeahead' search and use AbortController to cancel old requests as the user types new characters.
  4. Explain the difference between 'Canceling a request' (AbortController) and 'Ignoring a response' (Boolean Flag).

⚠️ Common Mistakes

  • Thinking that because the component unmounted, the network request stopped (it hasn't!).

  • Setting state on an unmounted component (React will sometimes warn about this, though it's less common in newer versions).

  • Not testing your data fetching on slow or unstable networks.

💼 Interview Questions

🎤 Mock Interview

Practice a live interview for Race Conditions & Cleanup