What is Axios Library in React

Axios is a popular, promise-based HTTP client that allows developers to make network requests from the browser to external servers. In this article, you will learn what the Axios library is, why it is highly preferred over the native Fetch API in React applications, how to install it, and how to perform basic data fetching operations within your React components.

What is Axios?

Axios is a lightweight, open-source library used to send HTTP requests. It runs on both client-side (the browser) and server-side (Node.js) environments. In a React application, Axios acts as a bridge between your frontend user interface and backend APIs, enabling you to fetch, send, update, and delete data smoothly.

Because Axios is promise-based, it allows you to write clean, readable asynchronous code using JavaScript’s async/await syntax or .then() and .catch() blocks.

Why Use Axios Instead of the Fetch API?

While modern browsers come with a built-in fetch() method, Axios offers several advantages that make it the preferred choice for React developers:

How to Install Axios in a React Project

To start using Axios in your React application, navigate to your project directory in the terminal and run one of the following commands:

Using npm:

npm install axios

Using yarn:

yarn add axios

How to Use Axios in React (Examples)

To fetch data in a React component, you typically combine Axios with the useState and useEffect hooks.

1. Making a GET Request

Below is an example of fetching a list of users from a public API when the component mounts.

import React, { useState, useEffect } from 'react';
import axios from 'axios';

function UserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/users')
      .then((response) => {
        setUsers(response.data); // Axios automatically parses JSON
        setLoading(false);
      })
      .catch((error) => {
        setError(error.message);
        setLoading(false);
      });
  }, []);

  if (loading) return <p>Loading users...</p>;
  if (error) return <p>Error: {error}</p>;

  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

export default UserList;

2. Making a POST Request

Here is how you can send new data to a server using a POST request with async/await.

import React, { useState } from 'react';
import axios from 'axios';

function CreateUser() {
  const [name, setName] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const response = await axios.post('https://jsonplaceholder.typicode.com/users', {
        name: name
      });
      console.log('User created successfully:', response.data);
    } catch (error) {
      console.error('Error creating user:', error);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input 
        type="text" 
        value={name} 
        onChange={(e) => setName(e.target.value)} 
        placeholder="Enter name"
      />
      <button type="submit">Add User</button>
    </form>
  );
}

export default CreateUser;

Summary of Axios Methods

Axios maps directly to HTTP request methods, making the API intuitive to use: