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:
- Automatic JSON Transformation: Unlike Fetch, which
requires you to manually convert response data using
response.json(), Axios automatically serializes and parses data to and from JSON. - Simpler Error Handling: Axios automatically throws
errors for any HTTP response status outside the 2xx range (such as 404
or 500 errors). With Fetch, you have to manually check
response.okto handle these errors. - Request and Response Interceptors: Axios allows you
to intercept requests or responses before they are handled by
thenorcatch. This is highly useful for automatically injecting authentication tokens (like JWT) into request headers. - Wide Browser Compatibility: Axios works out-of-the-box on older web browsers without requiring additional polyfills.
- Request Cancellation: Axios provides a straightforward way to cancel active HTTP requests if a user navigates away from a page, preventing memory leaks in React.
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 axiosUsing yarn:
yarn add axiosHow 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:
axios.get(url[, config])— Retrieves data.axios.post(url[, data[, config]])— Submits new data.axios.put(url[, data[, config]])— Updates existing data.axios.delete(url[, config])— Deletes data.