π 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 :
