How is Axios in React used: A Beginner's Guide 2025
Updated on Mar 07, 2025 | 9 min read | 18.2k views
Share:
For working professionals
For fresh graduates
More
Updated on Mar 07, 2025 | 9 min read | 18.2k views
Share:
Table of Contents
In modern React development, handling HTTP requests is a critical task for connecting with APIs and fetching data. One of the most effective tools for this is Axios in React. Axios is a promise-based HTTP client that simplifies the process of making asynchronous requests. It offers a straightforward API, making it easy to integrate into React applications for tasks like retrieving data or sending it to a server.
With Axios, developers can efficiently handle various request types, manage responses, and handle errors seamlessly. This beginner's guide will help you understand how to set up and use Axios in your React projects, ensuring you're equipped to work with APIs and data handling in 2025.
Ready to dive into Axios in React? Sign up for upGrad’s Full Stack Software Development Boot Camp and master HTTP requests, API integration, and more!
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 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);
});
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.
Check out our free technology courses to get an edge over the competition.
You can make the GET request using the “axios.get()” method. 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
});
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.
When working with Axios in React, you can handle responses in different ways depending on your specific requirements. 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
console.error('Error:', error);
});
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.How to Make POST Requests with Axios in React
Check Out upGrad’s Software Development Courses to upskill yourself.
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);
}
});
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.
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
});
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.
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);
});
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.
Axios interceptors in React are a powerful feature that allows you to intercept and modify requests and responses made with Axios globally. Interceptors act as middleware. They enable you to add custom logic before a request is sent or after receiving a response. This helps you centralise common functionality. You can now apply it consistently across your application.
To use interceptors, you start by importing Axios into your React component. Then, you can create request and response interceptors using the “axios.interceptors” object. Request interceptors modify the request configuration. This includes adding headers or tokens while response interceptors handle the response data. This allows you to modify it or handle errors.
Once the interceptors are set up, they will automatically be triggered for each corresponding request or response. For instance, a request interceptor can add an authentication token to every outgoing request. A response interceptor can modify the response data before it reaches your application code.
It is important to remember to clean up interceptors when they are no longer needed. This is important, especially in React components, to avoid memory leaks. This can be done by ejecting the interceptors. You can use the “axios.interceptors.request.eject()” and “axios.interceptors.response.eject()” methods.
Axios interceptors in React efficiently handle common tasks, implement global functionality, and customise your HTTP requests and responses, providing a seamless and consistent experience throughout your application.
Cancelling Axios requests in React involves using the CancelToken feature provided by Axios.
First, you create a cancel token using “axios.CancelToken.source()”. Then, while making a request, you pass the cancel token as the “cancelToken” property in the request configuration.
You call “cancel()” on the cancel token source to cancel the request. When the request is cancelled, it triggers an error that can be handled in the “.catch()” block. By cancelling requests, you can prevent unnecessary network traffic and handle scenarios where a request is no longer needed, improving the efficiency and responsiveness of your React application.
Here are some Axios best practices for React developers:
These are just a few best practices that React developers adopt. There are several more that you may adopt as a software developer. You could consider taking up an Executive Post Graduate Programme in Software Development if you already have experience in software development but wish to master its concepts better.
Mastering Axios in React is essential for building efficient, data-driven web applications. Axios simplifies handling HTTP requests, making it easier to fetch and send data to APIs. This guide covered the basics, from setting up Axios to making GET and POST requests, as well as handling responses and errors effectively. Understanding these concepts is key to integrating APIs seamlessly into your React projects.
By following this Axios React tutorial, you’ve learned foundational skills that will help you manage asynchronous operations and improve your React development process. As you continue working with React, leveraging Axios will enhance your ability to work with data and APIs in a more organized and efficient way.
To further expand your knowledge and skills, enrol in the Master of Science in Computer Science by upGrad. This course aims at teaching you all the in-demand skills in computer science and helps you ascend the corporate ladder with ease.
Visit upGrad to know more.
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