Introduction
To perform HTTP requests in React, developers commonly use:
- Fetch API
- Axios
Among these, Axios is one of the most popular libraries because it provides a cleaner syntax, automatic JSON conversion, better error handling, and many advanced features.
Axios simplifies API communication and makes asynchronous operations easier to manage in React applications.
What is Axios?
Axios is a popular JavaScript library used to make HTTP requests.
It helps applications:
- Fetch data from APIs
- Send data to servers
- Update resources
- Delete resources
Axios is promise-based and works smoothly with React applications.
Why Axios is Used in React?
React applications often need backend communication.
Examples:
- Fetching product data
- User login systems
- Updating profiles
- Sending forms
- Loading dashboard data
Axios makes these tasks simpler and cleaner compared to traditional methods.
Features of Axios
1. Promise-Based
Axios uses promises for handling asynchronous operations.
2. Automatic JSON Conversion
No need to manually convert responses using response.json().
3. Better Error Handling
Axios provides structured error responses.
4. Request and Response Interceptors
Useful for authentication and logging.
5. Supports All HTTP Methods
- GET
- POST
- PUT
- DELETE
- PATCH
6. Timeout Support
Requests can automatically stop after a certain time.
Installing Axios
Use npm to install Axios.
npm install axios
Importing Axios
import axios from "axios";
Basic Syntax of Axios
axios.get(url)
.then((response) => {
console.log(response.data);
});
Understanding Axios Response
Axios returns an object.
Example
axios.get(url)
.then((response) => {
console.log(response);
});
Important Axios Response Properties
| Property | Description |
|---|---|
| data | Actual response data |
| status | HTTP status code |
| headers | Response headers |
| config | Axios configuration |
GET Request in React Using Axios
GET requests are used to fetch data.
Example: Fetch Users
import { useEffect, useState } from "react";
import axios from "axios";
function App() {
const [users, setUsers] = useState([]);
useEffect(() => {
axios
.get("https://jsonplaceholder.typicode.com/users")
.then((response) => {
setUsers(response.data);
});
}, []);
return (
<div>
<h1>User List</h1>
{users.map((user) => (
<p key={user.id}>
{user.name}
</p>
))}
</div>
);
}
export default App;
How This Example Works?
Step 1
useEffect() runs after component mounts.
Step 2
Axios sends GET request.
Step 3
Server returns response.
Step 4
response.data contains actual data.
Step 5
React updates UI using state.
POST Request Using Axios
POST requests send data to servers.
Example
import axios from "axios";
const addUser = async () => {
const response = await axios.post(
"https://jsonplaceholder.typicode.com/users",
{
name: "John"
}
);
console.log(response.data);
};
PUT Request Using Axios
PUT requests update existing data.
Example
axios.put(
"https://jsonplaceholder.typicode.com/users/1",
{
name: "Updated User"
}
);
DELETE Request Using Axios
DELETE requests remove data.
Example
axios.delete(
"https://jsonplaceholder.typicode.com/users/1"
);
Using Async/Await with Axios
Async/Await provides cleaner code.
Example
import { useEffect, useState } from "react";
import axios from "axios";
function App() {
const [posts, setPosts] = useState([]);
useEffect(() => {
const fetchPosts = async () => {
const response = await axios.get(
"https://jsonplaceholder.typicode.com/posts"
);
setPosts(response.data);
};
fetchPosts();
}, []);
return (
<div>
{posts.map((post) => (
<p key={post.id}>
{post.title}
</p>
))}
</div>
);
}
export default App;
Error Handling in Axios
Always handle API errors properly.
Example
import { useEffect, useState } from "react";
import axios from "axios";
function App() {
const [error, setError] = useState(null);
useEffect(() => {
axios
.get("https://invalid-api.com")
.catch((err) => {
setError("Failed to fetch data");
});
}, []);
return (
<div>
{error && <h1>{error}</h1>}
</div>
);
}
export default App;
Using Try-Catch with Axios
import axios from "axios";
const fetchUsers = async () => {
try {
const response = await axios.get(
"https://jsonplaceholder.typicode.com/users"
);
console.log(response.data);
} catch (error) {
console.log(error);
}
};
Loading State with Axios
Loading states improve user experience.
Example
import { useEffect, useState } from "react";
import axios from "axios";
function App() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
axios
.get("https://jsonplaceholder.typicode.com/users")
.then((response) => {
setUsers(response.data);
setLoading(false);
});
}, []);
if (loading) {
return <h1>Loading...</h1>;
}
return (
<div>
{users.map((user) => (
<p key={user.id}>
{user.name}
</p>
))}
</div>
);
}
export default App;
Axios Interceptors
Interceptors allow developers to modify requests or responses.
Useful for:
- Authentication tokens
- Logging
- Error handling
Example
axios.interceptors.request.use((config) => {
config.headers.Authorization =
"Bearer token";
return config;
});
Common HTTP Methods in Axios
| Method | Purpose |
|---|---|
| GET | Fetch data |
| POST | Create data |
| PUT | Update data |
| DELETE | Remove data |
| PATCH | Partial update |
Axios vs Fetch API
| Feature | Axios | Fetch API |
|---|---|---|
| JSON Conversion | Automatic | Manual |
| Error Handling | Better | Basic |
| External Package | Required | Not required |
| Request Timeout | Supported | Limited |
| Simplicity | Easier | Moderate |
Real-Life Example: Product API
import { useEffect, useState } from "react";
import axios from "axios";
function Products() {
const [products, setProducts] = useState([]);
useEffect(() => {
const fetchProducts = async () => {
const response = await axios.get(
"https://fakestoreapi.com/products"
);
setProducts(response.data);
};
fetchProducts();
}, []);
return (
<div>
<h1>Products</h1>
{products.map((product) => (
<div key={product.id}>
<h2>{product.title}</h2>
<p>${product.price}</p>
</div>
))}
</div>
);
}
export default Products;
Advantages of Axios
1. Cleaner Syntax
Less code compared to Fetch API.
2. Automatic JSON Parsing
No need for response.json().
3. Better Error Handling
Provides detailed errors.
4. Supports Interceptors
Helpful for authentication systems.
5. Request Cancellation
Axios supports canceling requests.
Common Mistakes
1. Forgetting to Install Axios
Wrong:
import axios from "axios";
without installation.
Correct:
npm install axios
2. Using response Instead of response.data
Wrong:
setUsers(response);
Correct:
setUsers(response.data);
3. Missing Dependency Array
Wrong:
useEffect(() => {
fetchData();
});
Causes infinite API calls.
Correct:
useEffect(() => {
fetchData();
}, []);
4. Not Handling Errors
Always use:
- .catch()
- try-catch
5. Forgetting Loading State
Users should know data is loading.
Best Practices
Use Async/Await
Cleaner and readable code.
Handle Errors Properly
Always show meaningful error messages.
Organize API Calls
Create separate API files for large projects.
Use Environment Variables
Store API URLs securely.
Avoid Unnecessary Requests
Use dependency arrays correctly.
axios in Reactjs – Interview Questions
Q 1: What is Axios?
Q 2: Why use Axios instead of Fetch?
Q 3: How do you install Axios in React?
Q 4: Where are Axios requests usually made?
Q 5: Does Axios support request cancellation?
axios in Reactjs – Objective Questions (MCQs)
Q1. What is Axios in ReactJS?
Q2. Which method is used to make a GET request using Axios?
Q3. How do you install Axios in a React project using npm?
Q4. How can you handle a response from an Axios request?
Q5. Which of the following is true about Axios in ReactJS?
Conclusion
Axios is one of the most powerful and popular libraries for handling API requests in React applications.
Axios is widely used in:
- E-commerce applications
- Dashboard systems
- Social media apps
- Authentication systems
- Admin panels
Key benefits of Axios:
- Cleaner syntax
- Automatic JSON parsing
- Better error handling
- Interceptors support
- Async/Await compatibility
Learning Axios is essential for becoming a professional React developer and building modern data-driven applications effectively.