useEffect part 2
Fetching data in useEffect needs more than a fetch call: you must handle loading and error states, and protect against race conditions where a late, old response overwrites new data. This video also covers when you do not need an effect at all.
33.1 Fetch with loading and error
- Product takes an id prop and keeps two states: product (data) and error (message).
- The effect fetches /api/products/{id}, parses JSON and calls setProduct; the catch stores e.message in error.
- id is in the dependency array, so a new id fetches the new product.
- Render handles all three states: error -> error message, product still null -> Loading..., otherwise the product name.
import { useState, useEffect } from "react"; function Product({ id }) { const [product, setProduct] = useState(null); const [error, setError] = useState(null); useEffect(() => { fetch(`/api/products/${id}`) .then((res) => res.json()) .then((data) => setProduct(data)) .catch((e) => setError(e.message)); }, [id]); if (error) return <p>Error: {error}</p>; if (!product) return <p>Loading...</p>; return <h2>{product.name}</h2>;}-- first render --Loading...-- response arrives --# iPhone 16-- network off --Error: Failed to fetch33.2 The bug: wrong product on screen
- The user opens product 1 and immediately clicks product 2.
- Product 1's response is slow (300ms), product 2's is fast (50ms).
- The screen first shows Pixel 9 (correct), then switches to iPhone 16 even though the selected id is still 2.
Loading...# Pixel 9# iPhone 1633.3 How a race condition happens
- When id changed, the effect sent a new request but the old request was never cancelled.
- Product 2's response came first, then the late product 1 response also called setProduct and overwrote the data.
- Race condition: whichever response arrives last wins, even if it is the old one.
- Step 1
1.id = 1: request 1 sent (slow, 300ms)
- Step 2
2.id = 2: request 2 sent (fast, 50ms)
- Step 3
3.Response 2 arrives: Pixel 9 shown (correct)
- Step 4
4.Response 1 arrives late: setProduct overwrites
- Step 5
5.Screen shows iPhone 16 for id 2 (wrong!)
Whichever response arrives last ends up on screen
33.4 Fix 1: ignore flag
- Inside the effect, let ignore = false; call setProduct/setError only if ignore is still false.
- The cleanup sets ignore = true; React runs it before the next effect runs.
- When id changes the old effect's ignore becomes true, so the late product 1 response is ignored and the screen stays on Pixel 9.
useEffect(() => { let ignore = false; fetch(`/api/products/${id}`) .then((res) => res.json()) .then((data) => { if (!ignore) setProduct(data); }) .catch((e) => { if (!ignore) setError(e.message); }); return () => { ignore = true; };}, [id]);Loading...# Pixel 933.5 Fix 2: AbortController
- A browser API that actually cancels the request instead of just ignoring the response.
- Create a controller, pass controller.signal in the fetch options, call controller.abort() in the cleanup.
- An aborted fetch throws an AbortError: skip it in catch, otherwise a fake error appears on screen.
- Same result (Pixel 9) and no wasted network.
useEffect(() => { const controller = new AbortController(); fetch(`/api/products/${id}`, { signal: controller.signal, }) .then((res) => res.json()) .then((data) => setProduct(data)) .catch((e) => { if (e.name === "AbortError") return; setError(e.message); }); return () => controller.abort();}, [id]);Loading...# Pixel 9- Step 1
1.id changes from 1 to 2
- Step 2
2.React runs the old effect's cleanup: ignore = true / abort()
- Step 3
3.New effect runs and fetches product 2
- Step 4
4.Product 2 arrives: setProduct(Pixel 9)
- Step 5
5.Late product 1 response: ignored or already cancelled
Cleanup runs before the next effect
33.6 Comparison: ignore flag vs AbortController
| Point | Ignore flag | AbortController |
|---|---|---|
| What it does | Ignores the stale response | Cancels the request itself |
| Network | Old request still completes | Old request stopped, no waste |
| Extra handling | None | Skip e.name === "AbortError" in catch |
| Works with | Any async work (promises) | fetch and APIs that accept a signal |
33.7 StrictMode check
- In development StrictMode mounts the effect, cleans it up and mounts it again, so fetch 1 is logged twice.
- The first effect's ignore is already true after its cleanup, so setProduct runs only once and the screen shows iPhone 16.
useEffect(() => { let ignore = false; console.log("fetch", id); fetch(`/api/products/${id}`) .then((res) => res.json()) .then((data) => { if (!ignore) setProduct(data); }); return () => { ignore = true; };}, [id]);> fetch 1> fetch 1Screen: iPhone 1633.8 Common mistakes
- Using an effect for a derived value: the cart total kept in its own state and set from an effect renders 0 first and causes an extra re-render.
- Fix: calculate it during render; a value that can be built from props or state does not need state.
// Wrong: extra state + extra renderfunction CartTotal({ cart }) { const [total, setTotal] = useState(0); useEffect(() => { const sum = cart.reduce( (s, item) => s + item.price, 0); setTotal(sum); }, [cart]); return <p>Total: ₹{total}</p>;}// Right: calculated in render, no effectfunction CartTotal({ cart }) { const total = cart.reduce( (s, item) => s + item.price, 0); return <p>Total: ₹{total}</p>;}- Forgetting that fetch does not reject on a 404: check res.ok.
- No cleanup in a fetch effect: opens the door to race conditions.
33.9 You might not need an effect
| Situation | Where it belongs |
|---|---|
| Sync with an external system (network, timer, browser API, non-React widget) | useEffect |
| Derived value (total, filtered list) | Calculate during render |
| Work caused by a user action (place an order) | Event handler |
| Data fetching in real apps | TanStack Query or Next.js server components |
33.10 Rules for data fetching
- Write a cleanup in every fetch effect: ignore flag or AbortController.
- Handle both loading and error; check res.ok because fetch does not reject on 404.
- Put every value the effect uses into the dependency array.
- Do not add an effect for derived values.
33.11 Interview tips
- Race condition: when a dependency changes quickly, the late response of an old request overwrites new data.
- Fix it in the cleanup: set an ignore flag or cancel with AbortController.
- Effects are only for syncing with external systems; derived values go in render, user actions in handlers.
- In production prefer a library like TanStack Query (caching, dedupe, retries) for data fetching.