Category: react
Axios in react
Published on 15 Apr 2026
Explanation
Axios is a popular JavaScript library used
in React applications to make HTTP requests
to APIs such as GET, POST, PUT,
DELETE, etc. It helps communicate
between frontend
and backend services easily.
Code:
npm install axios
Explanation
Axios is commonly used instead of the
built-in fetch API because it provides
simpler
syntax, automatic JSON handling,
request cancellation, timeout
support, and better error handling.
Code:
import axios from 'axios';
axios.get('https://api.example.com/users')
.then(response =>
console.log(response.data))
.catch(error => console.log(error));
Explanation
Axios can send POST requests with data
to backend servers, which is useful for
form submissions and saving data.
Code:
axios.post('https://api.example.com/users', {
name: 'Praveen',
email: 'praveen@example.com'
})
.then(response =>
console.log(response.data));
Explanation
Axios allows setting headers such as
authorization
tokens when working with secured APIs.
Code:
axios.get('https://api.example.com/profile',
{
headers: {
Authorization: 'Bearer your_token_here'
}
});
Explanation
Axios supports creating reusable API
instances with
a base URL so multiple requests can
share configuration.
Code:
const api = axios.create({
baseURL: 'https://api.example.com'
});
api.get('/users');
Explanation
Axios is frequently used inside React
useEffect
hook to fetch data when components load.
Code:
import { useEffect } from 'react';
import axios from 'axios';
useEffect(() => {
axios.get('https://api.example.com/users')
.then(res => console.log(res.data));
}, []);