DEV Community

Cover image for Use Axios with React

Posted on

Use Axios with React

API Call in React Using Axios.


Most of the Web and Mobile apps need to communicate with server or external services to get and store data. This can be done by calling API. These apps use HTTP requests to communicate with APIs.

In react APIs can be consumed in various ways in which AXIOS and Fetch API are most popular.

In this article, we will discuss and implement Axios to access Dummy Rest API in a React application.

What is Axios?

Axios is a promise based lightweight HTTP client for browser and node.js.

Features at a glance

  • Make XMLHttpRequests from browser

This gives the ability to a web page to update just a part of a page without disrupting other areas.

  • Make HTTP request from node.js

As Axios works with node applications you can consume a third-party API, also this is useful in SSR(Server side rendering) for web applications.

  • Promise based support

Promise-based API gives you the ability to write more readable asynchronous code by taking advantage of native async and await javascript features.

  • Request and response interception

Interceptors are basically functions that Axios calls for every request and response.

You can intercept a request to transform it before Axios sends it or transform a response before Axios returns it to the caller.

  • Efficient error handling

As Axios built on promises, it has then() function for promise chaining and .catch() function for error handling.

You can also use response interceptors to handle errors. Response interceptor function takes two parameters, successHandler and errorHandler. You can write your own error handler to transform errors as you want.

  • Protection against CSRF

Axios supports token-based support to prevent CSRF.

  • Request cancellation support

Suppose we need to cancel the request when the user navigates from the current page to another after making an API call, then this can be done in Axios by using the cancellation token.

  • Automatic transformation for JSON data

Let's take a quick look at the basic usage of Axios

Using Axios to make HTTP requests is very easy.

Perform GET request

     method: 'get',
     url: 'https:/'
Enter fullscreen mode Exit fullscreen mode

Perform POST request


method: 'post',
      url: 'https:/',
      data: {
            email: '',
            password: abc123
Enter fullscreen mode Exit fullscreen mode

Above requests can also be made with inbuilt alias methods as

Enter fullscreen mode Exit fullscreen mode'https:/',{
            email: '',
            password: abc123
Enter fullscreen mode Exit fullscreen mode

Now let's consume Dummy Rest API in a React application

Installing Axios

To install Axios run the below command in terminal


npm install axios --save
Enter fullscreen mode Exit fullscreen mode

After installing, we need to import Axios into our application.
In our application, we will display a user list.

To Import Axios in UserList component add below line in UserList.js file

import axios from 'axios'
Enter fullscreen mode Exit fullscreen mode

Now it's time to call get API, to do this write the below function and call it from useEffect hook

function GetAllUSers() {
     .then(response => {
        const { data } =
    }).catch(error => {
Enter fullscreen mode Exit fullscreen mode

In GetAllUsers, we are calling users API and requesting data for page no 2 and getting a response in then block. Then we are destructuring data from the response and setting it into a UserData state variable. The result will be rendered as below.

Now before making a Post request let’s take a look at how we can configure the base instance of Axios.

Create file api.js in the src folder.

Import Axios and add below code block.

export default axios.create({

baseURL: `` 

Enter fullscreen mode Exit fullscreen mode

Here we are creating and exporting a new instance of Axios with baseURL.
Like baseURL we can also configure another Axios parameter like
Header, timeout, response type, and so on.

Now let's use the same base instance for making a POST request.
Add below import statement in UserList.js component

import baseInstance from '../api'
Enter fullscreen mode Exit fullscreen mode

Use this base instance for adding User. Here you can see we have just specified only the endpoint to add a user.

    const AddUser = async (event) => {
        await'api/users', {
            name: UserName,
            job: UserRole
        }).then(res => {
            alert(`Data saved successfully. 
                ID = ${}
                First name = ${}
                Role = ${}
                Created At = ${}`
        }).catch(error => {
Enter fullscreen mode Exit fullscreen mode

Also, you can see how we are using async and await with Axios.


In this article, we have used Axios to make HTTP requests in react applications.

The complete source for this article is available here on github.

Top comments (5)

ivan_jrmc profile image
Ivan Jeremic

Fetch is now supported everywhere, you can replace axios with fetch

sachinsmahajan profile image

Ok. I will try it.

whoshonit profile image

How can I pass header in request?

luski profile image

The title of this article is "use axios with react". Where is the "with react" part?

sachinsmahajan profile image
SachinSMahajan • Edited

After features of axios, I have given example of Get and Post request with react.