2025 Guide to Axios in React: Build Better Web Apps!
Updated on Jun 27, 2025 | 13 min read | 18.95K+ views
Share:
For working professionals
For fresh graduates
More
Updated on Jun 27, 2025 | 13 min read | 18.95K+ views
Share:
Table of Contents
Did you know? Over 52 lakh live websites in India are powered by React! Its widespread adoption makes it the go-to choice for tackling complex API integrations and efficient data management in modern web apps. |
Axios in React is a promise-based HTTP client used for making asynchronous API requests and handling responses. It simplifies data fetching, handling responses, and managing errors within your React app.
By using methods like GET, POST, PUT, and DELETE, Axios streamlines data management in modern web applications. In ReactJS, Axios helps optimize component performance by efficiently handling API calls and state updates.
In this blog, you'll learn how to set up Axios in React, use it for making requests, and handle errors effectively.
Looking to learn API integration and data management within React applications? upGrad’s Online Software Development Courses can equip you with tools and strategies to stay ahead. Enroll today!
Setting up Axios in React project is quick and straightforward. With just a few steps, you can integrate Axios to handle HTTP requests seamlessly in your application.
To enhance your expertise in making API requests and handling data efficiently with Axios in React, explore these upGrad courses designed for modern web development.
To set up Axios in React project, follow these steps:
Step 1: Install Axios
Start by installing Axios as a dependency in your project. You can use “npm” or “yarn” for this. Open your terminal and run the following command:
npm install axios
Step 2: Import Axios
In the component where you want to use Axios, import it at the top of your file:
import axios from 'axios';
Step 3: Make API Requests
You can now use Axios to make API requests. For instance, if you want to make a GET request to retrieve data from an API:
axios.get('https://api.example.com/endpoint')
.then(response => {
// Handle the response data
console.log(response.data);
})
.catch(error => {
// Handle any errors
console.error('Error:', error);
});
Explanation:
This code sends a GET request to the URL (https://api.example.com/endpoint). In the “.then()” block, you can access the response data using “response.data”. The “.catch()” block handles any errors during the request.
This setup allows you to easily handle API calls within your React components, making your app ready for data interactions.
Before going deeper into other requests, let’s first explore how to make GET requests with Axios in React.
To make GET requests with Axios in React, use axios.get('URL') inside your component's useEffect or event handler. Once the data is fetched, handle the response using .then() for successful results and .catch() for errors.
Here is an example:
axios.get('https://api.example.com/endpoint')
.then(response => {
console.log(response.data); // Do something with the response data
})
.catch(error => {
console.error('Error:', error); // Handle any errors
});
Output:
If the request is successful and the API responds with data, the response.data will be logged in the console.
{ id: 1, name: 'Sample Item', price: 100 }
If there is an error (e.g., if the endpoint doesn't exist or there's a network issue), the error message will be logged with console.error('Error:', error).
Error: [Error message with details about the issue]
Explanation:
In the above example, we make a GET request to the specified URL (https://api.example.com/endpoint). The “axios.get()” method returns a promise. Hence, we can use “.then()” to handle the successful response. We can use “.catch()” to handle any errors.
Also Read: Top 15 React Developer Tools 2024: Installation and Features
Once the request is made, let’s look at how to handle the responses effectively with Axios in React.
After making an API request, you can use the .then() method to handle successful responses and access the returned data. For errors, you can use .catch() to handle any issues that arise.
axios.get('https://api.example.com/endpoint')
.then(response => {
// Handle successful response
console.log(response.data);
})
.catch(error => {
// Handle error
console.error('Error:', error);
});
Output:
If the GET request is successful and the server returns data:
{ /* Example output from the server */ }
This will print the data returned from the endpoint.
If there is an error (e.g., the endpoint is incorrect or unreachable):
Error: Error: Network Error
This will print the error message, which could vary depending on the issue encountered. The error object contains detailed information about what went wrong.
Explanation:
In the code above, you handle the response using the “.then()” method. The response data can be accessed through “response.data”. If an error occurs during the request, it can be handled using the “.catch()” method.
Learn to manage API responses efficiently in React with Axios through upGrad’s free React JS course. Strengthen your web development expertise and start building dynamic applications now.
Now that you’ve seen how to make requests, let's focus on how to handle errors with Axios in React.
When using Axios in React, error handling is an important aspect of handling API requests. Axios provides several ways to handle errors. Here is an example using promises:
axios.get('https://api.example.com/endpoint')
.then(response => {
// Handle successful response
console.log(response.data);
})
.catch(error => {
// Handle error
if (error.response) {
// The request was made and the server responded with a status code outside the range of 2xx
console.error('Status:', error.response.status);
console.error('Data:', error.response.data);
} else if (error.request) {
// The request was made but no response was received
console.error('No response received:', error.request);
} else {
// Something happened in setting up the request that triggered an error
console.error('Error:', error.message);
}
});
Output:
Success: If the request is successful, it will log:
{data: "response data", status: 200, ...}
where the actual data returned from the API will be printed.
Error: If there's an error:
If the error is related to the response (status code outside 2xx range), you'll see:
Status: <status_code>
Data: <error_data>
If the request was made but no response was received:
No response received: <error.request>
If the error occurred during request setup:
Error: <error.message>
This ensures your application handles both success and error cases effectively.
Explanation
The “.catch()” block handles errors in the above code. The error object provides different properties for different scenarios. “error.response” is present when a response was received from the server. “error.request” is present when the request was made but no response was received. “error.message” is present when an error occurred while setting up the request.
Also Read: React Component Lifecycle: What Do You Need To Know
Now that you understand GET requests, let’s explore how to make POST requests with Axios in React.
Making POST requests with Axios in React allows you to send data to a server, typically for creating or updating resources. By using axios.post(), you can efficiently handle request payloads, manage headers, and process responses or errors within your React components.
You can make the POST request using the “axios.post()” method. Here is an example:
axios.post('https://api.example.com/endpoint', { data: 'example data' })
.then(response => {
console.log(response.data); // Handle the response data
})
.catch(error => {
console.error('Error:', error); // Handle any errors
});
Output:
1. Successful Response:
{ message: "Data received successfully", status: 200 }
2. Error Response (e.g., 404 Not Found):
Error: { response: { status: 404, data: { message: "Not Found" } } }
3. Network Error:
Error: Error: Network Error
4. Request Error (no response):
Error: { request: {...} }
Explanation
In the example above, we make a POST request to the URL (https://api.example.com/endpoint). The second argument to “axios.post()” is the data you want to send in the request body. In this case, we pass an object “{ data: ‘example data’ }”.
The “.then()” block handles the successful response, and you can access the response data using “response.data”. The “.catch()” block handles any errors during the request.
After sending a POST request, let's understand how to handle the response effectively with Axios in React.
When handling POST request responses with Axios in React, you can use the same techniques in handling GET request responses. Here is an example using promises:
axios.post('https://api.example.com/endpoint', { data: 'example data' })
.then(response => {
// Handle successful response
console.log(response.data);
})
.catch(error => {
// Handle error
console.error('Error:', error);
});
Expected Output:
1. Successful Response (2xx Status):
If the server returns a successful response, for example:
{ "message": "Data received successfully", "status": 200 }
The output would be:
{ message: "Data received successfully", status: 200 }
2. Error Response (Non-2xx Status):
If the server returns an error response (e.g., 404 Not Found or 500 Internal Server Error), for example:
{ "message": "Not Found" }
The output might look like:
Error: { response: { status: 404, data: { message: "Not Found" } } }
3. Network Error (No Response from the Server):
If the request is made but there's no response (e.g., if the server is down, or the URL is incorrect), the output might look like:
Error: Error: Network Error
4. No Response (e.g., Timeout or Server is Unreachable):
If the server doesn't respond, but the request is made, the output will contain information about the request, like this:
Error: { request: {...} }
This typically happens if there's a timeout or no network connection to the server.
Explanation:
In this code, the “.then()” block handles the successful response, and you can access the response data using “response.data”. If an error occurs during the request, it is caught in the “.catch()” block, where you can handle and log it.
To streamline your requests and responses, let's explore how to use Axios interceptors in React for better control.
Axios interceptors are a powerful tool in React for modifying requests and responses globally. By integrating Axios in React, developers can centralize functionality like authentication and error handling, improving code efficiency and consistency.
Use Case:
In an e-commerce app targeting Indian users, Axios interceptors can manage authentication tokens for secure user login across multiple platforms. By centralizing error handling, the app can provide consistent error messages, such as "Unauthorized access" or "Server error," improving user experience across the entire application.
Also read: Top 20 Real-Time React Projects and Ideas for Beginners in 2025
To maximize efficiency and avoid common pitfalls, here are the best practices for using Axios in React effectively.
When using Axios in React, it's crucial to follow best practices to ensure scalability and maintainability. These practices help in managing requests efficiently and avoiding common issues related to API calls.
Also Read: React JS Architecture: Implementation & Best Practices in 2024
Axios in React is used to manage asynchronous HTTP requests, enabling smooth interaction between your React components and external APIs. Effective handling of requests, responses, and errors is crucial for maintaining performance and ensuring a seamless data flow.
A common technical challenge is managing complex state updates and handling API errors without impacting the user experience. upGrad provides advanced resources to help you overcome these challenges and refine your skills in optimizing React applications.
In addition to the courses mentioned above, here are some free courses that can further strengthen your foundation in software engineering.
Curious how to optimize API calls and manage asynchronous data flow in React applications? Contact upGrad for personalized counseling and valuable insights. For more details, you can also visit your nearest upGrad offline center.
Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.
Start your journey with our free Software Development courses and gain the practical skills needed to succeed in the tech world!
Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.
Reference:
https://trends.builtwith.com/javascript/React
900 articles published
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology s...
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources