API Integration – Axios in React
Introduction
In modern React applications, communicating with backend APIs is a common requirement. While the Fetch API is built into the browser, many developers prefer Axios because it provides a cleaner syntax, automatic JSON handling, and advanced features such as interceptors and request cancellation.
Axios is one of the most widely used libraries for API integration in React.
What is Axios?
Axios is a promise-based HTTP client used to make requests to backend APIs from the browser or Node.js.
Axios supports:
- GET, POST, PUT, DELETE requests
- Automatic JSON data handling
- Request and response interception
- Better error handling
Why Use Axios Instead of Fetch?
Although Fetch API works well, Axios offers several advantages:
- Automatic JSON parsing
- Cleaner and shorter syntax
- Better error handling
- Request and response interceptors
- Supports request cancellation
- Works consistently across browsers
Installing Axios in React
npm install axios
Or using yarn:
yarn add axios
Basic Axios Syntax
axios.get(url)
.then(response => console.log(response.data))
.catch(error => console.error(error));
Axios returns the response directly in JSON format under response.data.
Making a GET Request in React
Example: Fetching Data on Component Load
import { useEffect, useState } from "react";
import axios from "axios";
function UsersList() {
const [users, setUsers] = useState([]);
useEffect(() => {
axios
.get("https://jsonplaceholder.typicode.com/users")
.then((response) => setUsers(response.data))
.catch((error) => console.error(error));
}, []);
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
export default UsersList;
Explanation:
- axios.get sends a GET request
- response.data contains API data
- No need to manually convert JSON
Making a POST Request in React
axios.post("https://jsonplaceholder.typicode.com/posts", {
title: "Axios in React",
body: "Learning API integration",
userId: 1,
})
.then(response => console.log(response.data))
.catch(error => console.error(error));
Axios automatically converts JavaScript objects into JSON.
Using Async and Await with Axios
const fetchUsers = async () => {
try {
const response = await axios.get(
"https://jsonplaceholder.typicode.com/users"
);
setUsers(response.data);
} catch (error) {
console.error(error);
}
};
This approach is cleaner and easier to read.
Handling Loading State with Axios
const [loading, setLoading] = useState(true);
useEffect(() => {
axios.get(url)
.then((res) => {
setData(res.data);
setLoading(false);
});
}, []);
Always show loading feedback for better user experience.
Error Handling in Axios
Axios automatically rejects promises for HTTP errors.
catch(error) {
console.error(error.response?.status);
}
You can access:
- error.response
- error.request
- error.message
Creating a Reusable Axios Instance
import axios from "axios";
const api = axios.create({
baseURL: "https://api.example.com",
headers: {
"Content-Type": "application/json",
},
});
export default api;
This improves code reusability and consistency.
Axios Interceptors
Interceptors allow you to modify requests or responses globally.
Example: Request Interceptor
api.interceptors.request.use((config) => {
config.headers.Authorization = `Bearer token`;
return config;
});
Common use cases:
- Adding auth tokens
- Logging requests
- Handling global errors
Canceling Requests in Axios
Axios supports request cancellation using AbortController.
const controller = new AbortController();
axios.get(url, { signal: controller.signal });
// cancel request
controller.abort();
Useful when components unmount.
Axios vs Fetch API
| Feature | Axios | Fetch API |
|---|---|---|
| Built-in | No | Yes |
| JSON handling | Automatic | Manual |
| Interceptors | Yes | No |
| Error handling | Better | Manual |
| Request cancel | Yes | Limited |
| Syntax | Cleaner | Verbose |
Best Practices for Using Axios in React
- Create a central Axios instance
- Handle loading and error states
- Use interceptors for auth
- Avoid calling APIs inside render
- Use environment variables for URLs
Common Mistakes with Axios
- Forgetting error handling
- Not canceling requests on unmount
- Hardcoding API URLs
- Mixing Fetch and Axios unnecessarily
- Overusing global state for API data
Interview Questions and Answers – Axios in React
1. What is Axios?
Axios is a promise-based HTTP client for making API requests.
2. Why use Axios instead of Fetch?
Axios provides cleaner syntax, automatic JSON parsing, and interceptors.
3. How do you make a GET request using Axios?
Using axios.get(url).
4. Does Axios automatically parse JSON?
Yes, response data is already parsed.
5. How does Axios handle errors?
It rejects the promise for HTTP error status codes.
6. What are Axios interceptors?
Functions that run before requests or after responses.
7. Can Axios cancel requests?
Yes, using AbortController.
8. Is Axios production-ready?
Yes, it is widely used in production applications.
9. Can Axios be used with Redux?
Yes, commonly used with Redux and Redux Toolkit.
10. Should Axios be used for all API calls?
It depends, but it is recommended for medium to large apps.
Your Feedback
Help us improve by sharing your thoughts
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.
