Axios in React: A Guide for Beginners
Last Updated :
23 Jul, 2025
React is one of the most popular JavaScript libraries for building user interfaces, and it works seamlessly with various data-fetching tools. Among these tools, Axios stands out as one of the easiest and most efficient libraries for making HTTP requests in React.
In this article, we’ll explore how to use Axios in a React application, making requests, handling responses, and handling errors.
What is Axios?
Axios is a promise-based HTTP client for JavaScript, which is used to make HTTP requests to fetch or send data to a server. It simplifies the process of handling requests by providing a cleaner API, better error handling, and support for features like request/response interceptors, cancellation, and more. It is also fully compatible with modern browsers and can be used in both the browser and NodeJS environments.
Key Features of Axios
- Promise-based API.
- Works in both NodeJS and browsers.
- Automatically transforms JSON data.
- Supports request and response interceptors.
- Allows easy handling of timeouts and cancellation of requests.
- Supports making GET, POST, PUT, DELETE, and other HTTP requests.
Before you install Axios your React project app should be ready to install this library.
To master React and integrate powerful libraries like Axios seamlessly, check out our comprehensive React course where we cover everything from basics to advanced concepts.
Setting Up Axios in a React Application
Before we start making HTTP requests with Axios, you need to install it. If you're starting a new React project, create one first using create-react-app (if you haven’t already).
Step 1: Install Axios
To install Axios, run the following command in your React project’s root directory:
npm install axios
Step 2: Import Axios into Your Component
In your React component, import Axios at the top
import axios from 'axios';
Step 3: Add Axios as Dependency
Install Axios library using the command given below
npm i axios
Project Structure

The Updated dependencies in package.json file.
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.6.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
Making HTTP Requests with Axios
Let’s start by looking at the two most common HTTP methods you’ll use: GET and POST.
1. GET Request
A GET request is used to retrieve data from an API. Here’s how to use Axios to fetch data from an API endpoint.
JavaScript
import React, { useEffect, useState } from "react";
import axios from "axios";
const App = () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
// Make GET request to fetch data
axios
.get("https://jsonplaceholder.typicode.com//posts")
.then((response) => {
setData(response.data);
setLoading(false);
})
.catch((err) => {
setError(err.message);
setLoading(false);
});
}, []);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
return (
<div>
<h1>Posts</h1>
<ul>
{data.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
};
export default App;
- State Management: The component uses useState to manage three states: data (stores fetched data), loading (tracks if the data is still loading), and error (handles any error that occurs during the data fetch).
- Data Fetching with Axios: Inside the useEffect hook, an API request is made using axios.get to fetch posts from the URL https://jsonplaceholder.typicode.com//posts. The response is stored in data, and loading is set to false when the fetch completes.
- Conditional Rendering: If data is still loading, it displays "Loading...". If an error occurs, it displays the error message. Otherwise, it renders a list of post titles from the fetched data.
Output
GET Request2. POST Request
POST requests are used to send data to the server. Let’s see how you can use Axios to send data via a POST request.
JavaScript
import React, { useState } from "react";
import axios from "axios";
const CreatePost = () => {
const [title, setTitle] = useState("");
const [body, setBody] = useState("");
const [responseMessage, setResponseMessage] = useState("");
const handleSubmit = (event) => {
event.preventDefault();
const newPost = {
title,
body,
};
// Make POST request to send data
axios
.post("https://jsonplaceholder.typicode.com//posts", newPost)
.then((response) => {
setResponseMessage("Post created successfully!");
})
.catch((err) => {
setResponseMessage("Error creating post");
});
};
return (
<div>
<h2>Create New Post</h2>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Post Title"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<textarea
placeholder="Post Body"
value={body}
onChange={(e) => setBody(e.target.value)}
/>
<button type="submit">Create Post</button>
</form>
{responseMessage && <p>{responseMessage}</p>}
</div>
);
};
export default CreatePost;
- State Management: The component uses useState to manage the title, body, and responseMessage states, which store the user input and the response message from the API.
- Form Handling and POST Request: On form submission (handleSubmit), a new post object is created with the title and body, and a POST request is made using axios.post to send the data to the API.
- Response Handling: After the request, if successful, a success message is shown ("Post created successfully!"); if there’s an error, it displays an error message ("Error creating post").
Output
Handling Errors in Axios
Error handling is an important part of working with HTTP requests. In the above examples, we used .catch() to handle any errors that occur during the request. However, Axios provides several ways to manage errors more efficiently:
Error Object: Axios provides an error object containing useful information such as the response status, error message, and more. We can access it like this:
JavaScript
axios
.get("https://jsonplaceholder.typicode.com//invalid-endpoint")
.catch((error) => {
if (error.response) {
// Server responded with a status other than 2xx
console.log("Response error:", error.response);
} else if (error.request) {
// No response was received
console.log("Request error:", error.request);
} else {
// Something went wrong setting up the request
console.log("Error:", error.message);
}
});
You can use status codes to handle specific error cases, such as redirecting the user if a 401 Unauthorized error occurs, or showing a different message for a 404 Not Found error.
Output
Handling Errors in AxiosBest Practices for Using Axios in React
- Use Axios with async/await: For cleaner code, consider using async/await with Axios.
JavaScript
const fetchData = async () => {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com//posts');
setData(response.data);
} catch (error) {
setError(error.message);
}
};
- Use Axios Instances: For scalability and easier configuration, you can create Axios instances that can be reused across components.
JavaScript
const axiosInstance = axios.create({
baseURL: "https://jsonplaceholder.typicode.com/",
timeout: 1000,
});
axiosInstance
.get("/posts")
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
- Handle Loading States: Always handle loading and error states in your UI so users have feedback while waiting for data.
Response Objects in Axios
When you send a request to the server, you receive a response object from the server with the properties given below...
- data: You receive data from the server in payload form. This data is returned in JSON form and parse back into a JavaScript object to you.
- status: You get the HTTP code returned from the server.
- statusText: HTTP status message returned by the server.
- headers: All the headers are sent back by the server.
- config: original request configuration.
- request: actual XMLHttpRequest object.
Error Object
You will get an error object if there will be a problem with the request. Promise will be rejected with an error object with the properties given
- message: Error message text.
- response: Response object (if received).
- request: Actual XMLHttpRequest object (when running in a browser).
- config: Original request configuration.
Conclusion
Axios is a powerful and easy-to-use HTTP client that simplifies making API requests in React applications. With its built-in features like automatic JSON parsing, request and response interceptors, and error handling, Axios is an excellent choice for handling HTTP requests in your React projects.
Axios in React: A Guide for Beginners
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability.React.jsWhy Use React?Before React, web development faced issues like slow DOM updates
7 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDom is a core react package that provides methods to interact with the Document Object Model or DOM. This package allows developers to access and modify the DOM. Let's see in brief what is the need to have the package. Table of ContentWhat is ReactDOM ?How to use ReactDOM ?Why ReactDOM is used
3 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite
5 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. In this article, we'll explore ReactJS keys, understand their importance, how the
5 min read
Components in React
React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.What are Reactjs Functio
5 min read
React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
4 min read
ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
2 min read
ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he
5 min read
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects