Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 7.7 — Fetching Data in an Effect
React · Example 2 of 4

A real race condition: the old response wins

The bug: the page says user 2 is selected but shows Asha (user 1). The fast request for user 2 finished first; the slow, outdated request for user 1 finished last and overwrote it.

You can load data in an effect by tracking loading, error and success states, but you must stop old responses from overwriting new ones (a race condition) with an ignore flag or an AbortController; in real apps a framework or a data library usually does this better.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a useEffect that loads /api/posts?page= + page with fetch, ignores stale responses, and stores the JSON in posts.

02

Rewrite the previous answer with AbortController.

Explain it without notes

01

How would you fetch data in a useEffect? Cover loading, error and success.

02

Describe a race condition in data fetching and two ways to prevent it.

03

Why can't the effect function be async?

04

Why do frameworks and data libraries usually fetch better than hand-written effects?

A real race condition: the old response wins

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

request user 1 (600 ms)
request user 2 (100 ms)
response for user 2 -> setUser
response for user 1 -> setUser
Selected user 2, screen shows: Asha