React API Calls using Fetch & Axios β Complete Integration Guide (2025)
Introduction β Why API Calls Matter in React
React.js apps often need to interact with external servicesβREST APIs, GraphQL endpoints, or backend servers. Whether you’re loading user data, submitting forms, or integrating with third-party services, making API calls is essential.
React supports multiple ways to fetch data, but the most common are:
fetchβ native browser API- Axios β a popular, feature-rich HTTP client
In this guide, youβll learn:
- How to perform GET/POST requests using
fetchandaxios - How to handle loading, success, and error states
- When to use each approach
- Best practices for reusable API logic in React
1. Using the Native fetch API
fetch() is built into modern browsers and provides a promise-based interface to make HTTP requests.
Basic GET Request:
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then((res) => {
if (!res.ok) throw new Error('Failed to fetch');
return res.json();
})
.then((data) => setPosts(data))
.catch((err) => setError(err));
}, []);
POST Request:
fetch('/api/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ title: 'React Rocks!' }),
});
2. Making API Calls with Axios
Axios simplifies HTTP calls by handling JSON parsing, request cancellation, and interceptors.
Install Axios:
npm install axios
Axios GET Request:
import axios from 'axios';
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then((res) => setPosts(res.data))
.catch((err) => setError(err));
}, []);
Axios POST Request:
axios.post('/api/posts', {
title: 'Learning Axios with React',
content: 'Axios makes HTTP easier',
});
3. Fetch vs Axios β Feature Comparison
| Feature | fetch | axios |
|---|---|---|
| Built-in | Yes | No (needs install) |
| JSON parsing | Manual .json() | Automatic |
| Interceptors | Not supported | Yes |
| Request cancellation | With AbortController | With cancel token |
| Default headers | None | application/json |
| Error handling | Manual | Better structured |
4. Reusable API Call Functions
With fetch:
export async function fetchData(url) {
const res = await fetch(url);
if (!res.ok) throw new Error('Error fetching data');
return await res.json();
}
With Axios:
import axios from 'axios';
export const apiClient = axios.create({
baseURL: '/api',
headers: { 'Content-Type': 'application/json' },
});
Use Axios interceptors to add tokens or log errors
5. useEffect + API Calls Pattern
useEffect(() => {
let isMounted = true;
fetchData('/api/data')
.then(data => isMounted && setData(data))
.catch(err => console.error(err));
return () => {
isMounted = false;
};
}, []);
Prevents state update on unmounted component
Consider AbortController for fetch cleanup
6. API Call Use Cases in React
| Use Case | Method | Tool Suggestion |
|---|---|---|
| Get user data | GET | fetch, axios |
| Submit form | POST | axios |
| Update profile | PUT/PATCH | axios, fetch |
| Delete item | DELETE | axios |
| Auth with token | Any | axios + interceptors |
Best Practices
Use try/catch with async/await for readability
Manage loading and error states
Cancel long-running requests on unmount
Extract API logic into separate utility files
Handle HTTP error codes gracefully
Summary β Recap & Next Steps
Both fetch and Axios allow you to make powerful API calls in React. While fetch is native and lightweight, Axios offers a more ergonomic and feature-rich developer experienceβespecially in larger applications.
Key Takeaways:
- Use
fetch()for native, simple API calls - Use Axios for larger apps with interceptors and error handling
- Manage loading and errors using
useStateanduseEffect - Cancel requests and avoid memory leaks
- Abstract logic for reusability and scalability
Real-World Relevance:
Used in production apps for dashboards, login flows, file uploads, and real-time data sync in apps like Airbnb, GitHub, and Slack.
FAQ Section
Should I use fetch or axios in React?
Use fetch for simple use cases and Axios for advanced needs like interceptors, auto JSON parsing, and cancellation.
How do I handle API errors?
Use try/catch or .catch() to handle failures and show fallback UI or messages.
Can I cancel an API request in React?
Yes. Use AbortController with fetch or CancelToken with Axios.
Is useEffect required for API calls?
For component-based data loading, yes. It ensures the fetch runs after render and not during the render phase.
How do I show a loading spinner during API calls?
Use a loading state with conditional rendering:
{loading ? <Spinner /> : <Data />}
Share Now :
