Data Fetching in React
In modern web apps, components often need to display data from a server. In React, API calls are considered 'side effects' because they interact with the outside world. These are typically handled inside the useEffect hook to ensure they run at the correct point in the component lifecycle.
The Fetch API vs. Axios
You have two primary choices for making HTTP requests: the native browser fetch() API or the popular third-party library Axios.
| Feature | Fetch API | Axios |
|---|---|---|
| Installation | Built-in (No install) | Requires `npm install axios` |
| JSON Parsing | Manual (`res.json()`) | Automatic |
| Error Handling | Manual (check `res.ok`) | Automatic for 4xx/5xx status |
| Interceptors | No | Yes (Great for Auth tokens) |
| Timeout Support | Manual (AbortController) | Simple config property |
Handling Loading & Error States
A professional API implementation must handle three distinct states: Loading (the request is in flight), Error (the request failed), and Data (the request succeeded).
Best Practices
- Cleanup after yourself: Use an
AbortControllerto cancel requests if the component unmounts before the request finishes. - Abstract your API logic: Move fetch calls to a separate
services/folder to keep components clean. - Avoid 'Waterfall' fetches: If two API calls don't depend on each other, use
Promise.all()to fetch them in parallel. - Consider a library: For complex apps, use TanStack Query (React Query) to handle caching, re-fetching, and background updates automatically.