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:
- Boolean Flag: Use a variable to track if the current effect is still valid.
- AbortController: Built-in browser API to actually cancel the network request. This is the preferred modern way.
💻 Code Example
code
1import React, { useState, useEffect } from 'react';23function ProductDetails({ productId }) {4 const [product, setProduct] = useState(null);56 useEffect(() => {7 // 1. Create the controller8 const controller = new AbortController();9 const signal = controller.signal;1011 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 };2425 fetchProduct();2627 // 2. CLEANUP: Abort the fetch if productId changes or component unmounts28 return () => {29 controller.abort();30 };31 }, [productId]);3233 if (!product) return <div>Loading...</div>;34 return <h1>{product.name}</h1>;35}
🏋️ Practice Exercise
- Simulate a slow network in Chrome DevTools and build a component that switches between different data tabs. Observe race conditions without cleanup.
- Implement the 'Boolean Flag' approach to solving race conditions.
- Build a 'Typeahead' search and use AbortController to cancel old requests as the user types new characters.
- 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
Was this topic helpful?