Data Fetching, AbortController & Error States
Handle loading, error, and empty UI states cleanly while preventing race conditions using AbortController.
What you'll learn
- Model async UI with explicit loading, error, and data states
- Prevent stale response race conditions with AbortController in effect cleanup
- Always handle non-2xx HTTP responses (`if (!res.ok) throw ...`)
When a user switches tabs quickly (courseId = 1 then courseId = 2), the slower request for 1 might arrive after 2 and overwrite the screen with stale data. Passing an AbortController signal to fetch(url, { signal }) and calling controller.abort() in the useEffect cleanup eliminates this race condition cleanly.
Fill-in-the-Blank Exercise
Cancel Stale Fetch on Cleanup
Create an AbortController and abort it when the effect cleans up.
const controller = new ();
fetch(url, { signal: controller.signal });
return () => controller.();Live Async State Machine Demo
No console output yet. Try calling console.log(...) in JS.
Check Your Understanding
1. Why should a React data-fetching useEffect use AbortController (or an ignore flag) in its cleanup function?
Finished this lesson?
Your progress is saved locally in your browser, no account needed.