Chapter 6 of 8
Course Progress0 of 8 completed (0%)

Modern Full-Stack & React Internals · Chapter 6 · ~15 min · Intermediate

Data Fetching, Race Conditions & Custom Hooks

Build robust client-side data pipelines: handling loading/error/success states, cancelling stale requests with AbortController, avoiding async race conditions, and extracting reusable custom hooks.

  • Handle asynchronous fetch lifecycles (loading, error, empty, data)
  • Neutralize network race conditions using AbortController signals
  • Design and package reusable custom hooks following Hook Rules
  • Implement client-side query caching and stale-while-revalidate patterns

Data Fetching, Race Conditions & Custom Hooks: learn it visually

Build robust client-side data pipelines: handling loading/error/success states, cancelling stale requests with AbortController, avoiding async race conditions, and extracting reusable custom hooks.

Data Fetching, Race Conditions & Custom HooksBuild robust client-side data pipelines: handling loading/error/success states, cancelling stale requests with AbortController, avoiding async race conditions, and extracting reusable custom hooks.UNDERSTANDData FetchingFOLLOW THE FLOWRace ConditionsAPPLY ITCustom HooksData Fetching, Race Conditions & Custom HooksBuild robust client-side data pipelines: handling loading/error/success states, cancelling stale requests with AbortController, avoiding async race conditions, and extracting reusable custom hooks.UNDERSTANDData FetchingFOLLOW THE FLOWRace ConditionsAPPLY ITCustom Hooks

1The 4 States of Asynchronous UI

Data fetching in React is never just about the happy path. A production-ready user interface must cleanly handle all four states of the data lifecycle:

1. Idle / Empty

Initial state

User hasn't searched or no data exists yet.

2. Loading

Inflight request

Show skeleton loader, spinner, or progress bar.

3. Success

Data resolved

Render data items and interactive controls.

4. Error

Network / HTTP failure

Display error message and actionable Retry button.

Wrong idea: Naive fire-and-forget fetch inside useEffect

fetch('/api/user').then(res => setData(res));
Uncontrolled async resolution · attempts to set state on unmounted tree

Triggering fetch() and blindly calling setData(res) inside .then(), ignoring unmounted components and interleaved requests.

Real system: Declarative fetch with AbortController signal

const c = new AbortController(); fetch(url, { signal: c.signal });
return () => c.abort();
Immediate network abort · zero stale state updates

Passing signal: controller.signal to fetch() and returning () => controller.abort() in effect cleanup, cancelling superseded network promises.

2The Race Condition: When Fast Overcomes Slow

Consider an auto-complete search bar. The user types "React":

  1. User types "Rea" → sends Request A.
  2. User types "React" → sends Request B.

In an ideal world, Request A returns first, then Request B. However, networks are asynchronous and unpredictable. Request B might hit an edge cache and return in 80ms, while Request A routed through a congested server and returns in 600ms.

Result: Request A finishes LAST and executes setData(resultsForRea), clobbering the screen with outdated data!

3Cancelling Stale Requests with AbortController

The standard browser solution is AbortController. By linking an abort signal to your fetch() call and aborting in the useEffect cleanup function, React cancels the outgoing request the instant the dependency changes or the component unmounts:

useEffect(() => {
  // 1. Create a controller instance:
  const controller = new AbortController();

  async function loadData() {
    try {
      setIsLoading(true);
      // 2. Pass signal to fetch:
      const res = await fetch(`/api/search?q=${query}`, {
        signal: controller.signal,
      });
      const data = await res.json();
      setResults(data);
    } catch (err: any) {
      // 3. Ignore AbortError - it's an intentional cancellation!
      if (err.name !== "AbortError") {
        setError(err.message);
      }
    } finally {
      setIsLoading(false);
    }
  }

  loadData();

  // 4. CLEANUP: Abort superseded network request!
  return () => {
    controller.abort();
  };
}, [query]);

Predict first

What happens if you do NOT check err.name !== 'AbortError' in the catch block?

4Packaging Logic into Custom Hooks: useFetch

Writing 25 lines of useState, AbortController, and error handling in every component violates DRY (Don't Repeat Yourself). Instead, extract the lifecycle into a Custom Hook:

import { useState, useEffect } from "react";

interface FetchState<T> {
  data: T | null;
  isLoading: boolean;
  error: string | null;
}

export function useFetch<T>(url: string): FetchState<T> {
  const [data, setData] = useState<T | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const controller = new AbortController();
    setIsLoading(true);
    setError(null);

    fetch(url, { signal: controller.signal })
      .then((res) => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.json();
      })
      .then((json) => setData(json))
      .catch((err) => {
        if (err.name !== "AbortError") setError(err.message);
      })
      .finally(() => setIsLoading(false));

    return () => controller.abort();
  }, [url]);

  return { data, isLoading, error };
}

// In any component:
const { data: users, isLoading, error } = useFetch<User[]>("/api/users");

5Hands-On: Async Race Condition & Latency Simulator

Simulate real network latency. Toggle between vulnerable fetching and AbortController protection to observe how out-of-order responses overwrite screen state:

Interactive Network Race Condition & Latency Simulator

Simulation Scenario:
Network Jitter Simulation

The user types "Rea" (Query 1), experiencing 1,800ms high server latency. Immediately after, the user types "React" (Query 2), which hits a fast edge cache in 600ms.

Concurrent Network Requests:
Q1: "Rea"
Slow Query (1800ms latency)
Idle / Inflight
Q2: "React"
Fast Query (600ms latency)
Idle / Inflight
What the User Actually Sees on Their Screen:Input: "React"
Results for 'React' (Cached)

⚠️ Race Condition Disaster: Even though the user finished typing "React", the slow response for "Rea" arrived last and clobbered the user interface!

6Bug Hunt: Fix the Search Typeahead Race Condition

A customer search bar suffers from race conditions when users type fast. Add an AbortController and return an effect cleanup below:

Search Typeahead Race Condition Bug Hunt
TypeScript JSX

🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.

Need a hint?
  • Instantiate const controller = new AbortController(); inside the effect.
  • Pass { signal: controller.signal } as options to fetch(...).
  • Return a cleanup function: return () => controller.abort();.

7Chapter Knowledge Challenge

Verify your data fetching, cancellation, and custom hook fundamentals:

Concept Check 1 of 3
1

What is the root cause of an asynchronous race condition in a React search input?

Concept Check 2 of 3
2

How does AbortController communicate cancellation to the browser's fetch API?

Concept Check 3 of 3
3

According to the Rules of Hooks, what distinguishes a Custom Hook from an ordinary JavaScript helper function?

8Recap & Architectural Takeaways

  • 4 UI States: Always model Idle, Loading, Success, and Error states explicitly.
  • Race Conditions: Never assume requests arrive in order. Use AbortController to cancel stale in-flight fetches.
  • Ignore AbortError: Always check err.name !== "AbortError" in your error handling.
  • Extract Custom Hooks: Encapsulate data fetching, caching, and abort lifecycles into reusable hooks like useFetch.

Ready for Server Rendering & React Server Components in Chapter 7?

Enjoying this free lesson? Your support helps us build more free animated chapters.

Support Us