View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

How is Axios in React used: A Beginner's Guide 2025

By Pavan Vadapalli

Updated on May 12, 2025 | 17 min read | 18.58K+ views

Share:

Did You Know: NPM download statistics reveal that Axios consistently exceeded 200 million downloads per month last year, highlighting its widespread adoption and strong community support.

Axios in React is used to make HTTP requests to external APIs or servers. It simplifies handling asynchronous operations with methods like GET, POST, PUT, and DELETE. 

Axios also supports features like interceptors for request/response modification, automatic JSON parsing, and error handling, making it a popular choice for managing data fetching in React applications.

In this blog, you'll learn how to set up Axios in React, use it for making requests, and handle errors effectively.

Ready to dive into Axios in React? Sign up for upGrad’s Online Software Development Courses and master HTTP requests, API integration, and more!

How to Set Up Axios in React Project?

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.

This setup allows you to easily handle API calls within your React components, making your app ready for data interactions.

Explore these top courses to sharpen your React skills, focusing on essential tools and strategies for building efficient, scalable applications and mastering modern web development.

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]

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.

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months

Job-Linked Program

Bootcamp36 Weeks

Ready to dive deeper into React? Take your first step towards learning software development with upGrad's AI Driven Full Stack Development Bootcamp. Gain access to 300+ hours of content, 7+ case studies and projects by industry experts!

How to Handle Responses 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.

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.

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.

Code 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

How to Make POST Requests with Axios in React?

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: {...} }

Code 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.

Handling POST Request Responses 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.

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.

Enhance your understanding of Generative AI in software development by enrolling in upGrad’s Online Generative AI Mastery Certificate Program. Dive into advanced techniques and advance your AI expertise. Join today!

How to Use Axios Interceptors in React?

Axios interceptors are a powerful feature in React that allow you to intercept and modify requests and responses globally. They act as middleware, enabling you to add custom logic before a request is sent or after receiving a response. This functionality is particularly useful for centralizing common tasks like adding authentication tokens or handling global error logic.

Here’s how to effectively use Axios interceptors in your React application:

What Are Axios Interceptors?

Interceptors allow you to:

  • Modify requests: Customize request headers, add authentication tokens, etc.
  • Handle responses: Modify response data or handle errors globally before the data reaches your app.

Steps to Use Axios Interceptors in React

1. Import Axios into Your Component

You first need to import Axios in React into your component or set it up globally.

2. Create Request and Response Interceptors

You can now set up request interceptors (to modify the request) and response interceptors (to modify the response).

A. Request Interceptor

A request interceptor allows you to modify the outgoing request configuration. For example, you might want to add an authentication token to every request.

B. Response Interceptor

A response interceptor allows you to modify the response data globally. For example, you can handle common errors (e.g., 401 Unauthorized) or modify the response data before passing it to your app.

3. Eject Interceptors When No Longer Needed

It’s important to clean up interceptors, especially in React components, to prevent memory leaks.

You can eject interceptors using the axios.interceptors.eject() method.

Why Use Axios Interceptors?

  • Centralize Logic: Instead of adding authentication headers in every request, interceptors allow you to handle it in one place.
  • Global Error Handling: Easily handle errors such as token expiration, server issues, etc., in one location.
  • Consistency: Modify or handle requests and responses globally to ensure consistency across the app.

Use Cases for Axios Interceptors:

  • Authorization Tokens: Add authentication tokens to every request.
  • Global Error Handling: Catch global errors, like 401 (unauthorized) or 500 (server error).
  • Modify Responses: Modify response data, like formatting dates or standardizing field names.

Also Read: 13 Best React Project Ideas & Topics for Beginners 2024

How to Cancel Axios Requests in React?

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.

What Are the Best Practices for Using Axios in React?

Here are some Axios best practices for React developers:

  • Use Axios’ request cancellation feature to cancel requests when they are no longer needed, preventing unnecessary network traffic.
  • Implement error handling using “.catch()” to gracefully handle errors and provide appropriate feedback to the user.
  • Utilise Axios’ interceptors to add global request headers, handle authentication, modify responses, or implement custom logic.
  • Encapsulate API calls in separate modules or functions for better organisation and reusability.

These are just a few best practices that React developers adopt. There are several more that you may adopt as a software developer.

Also Read: React JS Architecture: Implementation & Best Practices in 2024

Enhance Your Coding Skills with upGrad!

Learning Axios in React streamlines handling HTTP requests, making it easier to integrate APIs and manage data efficiently. By mastering these concepts, you can enhance your React development and handle asynchronous operations with ease.

upGrad offers comprehensive programs that provide hands-on experience with advanced technology and industry experts.

In addition to the courses mentioned above, here are some free courses that can further strengthen your foundation in software engineering.

Feeling uncertain about where to go next in your software development path? Consider availing upGrad’s personalized career counseling. They can guide you in choosing the best path tailored to your goals. You can also visit your nearest upGrad center and start hands-on training today!

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 Link:
https://npm-stat.com/charts.html

Frequently Asked Questions (FAQs)

1. Is Axios a REST API?

2. Is Axios async or sync?

3. Why is Axios better than Fetch?

4. Is Axios in React suitable for file uploads?

5. What happens if an Axios request times out?

6. What is a React Query?

7. How do I debug Axios requests?

8. How do I handle multiple Axios requests at once?

9. Can I use Axios for making POST requests in React?

10. Can I use Axios with Node.js?

11. Is Axios compatible with all browsers?

Pavan Vadapalli

900 articles published

Get Free Consultation

+91

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

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

upGrad KnowledgeHut

upGrad KnowledgeHut

Angular Training

Hone Skills with Live Projects

Certification

13+ Hrs Instructor-Led Sessions

upGrad

upGrad

AI-Driven Full-Stack Development

Job-Linked Program

Bootcamp

36 Weeks