Fetch API
Master data fetching in React with the Fetch API. Learn patterns for loading states, error handling, cancellation, and the production patterns senior engineers use.
Last reviewed: January 2025
🔍 What Is It?
The Fetch API is a browser-native HTTP client that returns Promises:
const response = await fetch('/api/claims');
const data = await response.json();Key characteristics:
- →Does not throw on HTTP errors — fetch only rejects on network failure. A 404 or 500 response resolves successfully. You must check
response.okmanually. - →Two-step process — first await the response, then await the body (
response.json(),response.text(), etc.) - →AbortController — cancel in-flight requests with an AbortSignal
🎯 Why Do We Need It?
React components need data from APIs. The Fetch API is the simplest way to get it without adding dependencies. Understanding fetch is foundational even if you later use Axios or React Query, because those libraries build on the same concepts.
🏗️ What Happens in Real Projects?
Direct fetch usage in React:
- →Simple data loading in a custom hook
- →One-off POST requests (form submission, action buttons)
- →Streaming responses (Server-Sent Events, ReadableStream)
- →Uploading files with FormData
⚙️ How It Works
In React, always use fetch inside useEffect:
- Component mounts
- useEffect runs after render
- fetch() starts the request
- Response arrives, setState updates the component
- Component re-renders with the data
AbortController:
Cancel the request in the useEffect cleanup function to prevent setState on unmounted components and to cancel stale requests when dependencies change.
💻 Example
Fetch Patterns in React — A production-ready fetch wrapper and custom hook.
🤔 Common Confusions
❓ Why does fetch not throw on 404 or 500?
fetch only rejects (throws) on network failures — no internet, DNS failure, CORS error. HTTP error responses (4xx, 5xx) are considered successful responses from fetch's perspective. Always check response.ok (true for 200-299) and throw manually if it is false.
❓ What is AbortController and when do I need it?
AbortController lets you cancel a fetch request. In React, return controller.abort() from useEffect cleanup. Without it: (1) if the component unmounts before the request completes, setState is called on an unmounted component; (2) if the dependency changes rapidly (e.g., user types in a search), multiple requests are in flight and the last to resolve wins (race condition).
🚨 Common Production Issues
**Bug: Forgetting response.ok check** — fetch resolves for 404/500. Without checking response.ok, error responses are treated as success.
**Race condition** — User changes a filter quickly; multiple requests in flight; last to resolve overwrites the result. Fix: AbortController cancels the previous request when the dependency changes.
**Memory leak** — setState called after component unmounts. Fix: AbortController in useEffect cleanup.
**For production apps** — Do not use raw fetch in components. Use React Query which handles all of these issues automatically.
✅ Best Practices
Create a centralised fetch wrapper for auth headers, base URL, and error parsing
Always check response.ok and throw on HTTP errors
Use AbortController in useEffect cleanup for cancellation
For production data fetching, use React Query instead of raw fetch
Never fetch in the component body — always in useEffect or event handlers
Use TypeScript generics: fetch<T>() for type-safe responses
🏛️ Architect's Note
Raw fetch in useEffect is fine for learning and simple cases. In production, use React Query (TanStack Query). It handles caching, background refetching, deduplication, loading/error states, cancellation, and stale-while-revalidate automatically. The custom fetch hook pattern shown here is what React Query does internally — but with much more sophistication. If you find yourself building a fetch cache, you are reinventing React Query.
💬 Frequently Asked Questions
🎯 Key Takeaways
🔗 Related Topics
🎯 Practice this topic in interviews
↗ Where this topic fits
React Technology Guide
Return to the React learning hub.
Frontend Engineer Career Path
A beginner-friendly journey through web foundations, React, production frontend engineering, and interview preparation.
Python Developer Career Path
A practical route through Python fundamentals, automation, backend basics, testing, projects, interview preparation, and career growth.
Sources
Sources / References
Use these React references to verify the concept in official docs and continue into the most relevant SplashRide pages.
Official documentation
Related SplashRide pages
SplashRide React learning path
Browse the full React topic collection and learning order on SplashRide.
React Interview Prep
Practice React interview questions and scenario-based answers.
Frontend Engineer Career Path
A beginner-friendly journey through web foundations, React, production frontend engineering, and interview preparation.
Python Developer Career Path
A practical route through Python fundamentals, automation, backend basics, testing, projects, interview preparation, and career growth.
Axios
Master Axios in React — the most popular HTTP client library. Learn instance configuration, interceptors, error handling, and the patterns senior engineers use in enterprise applications.
useEffect
Master useEffect — the hook for synchronising React components with the outside world. Learn the dependency array, cleanup functions, and how to avoid the most common production bugs.