Menu

What is Axios?

Using Axios

What is Axios?

Axios is a popular third-party library for making HTTP requests. It does the same job as fetch(), with a few conveniences.

Installation

bash

npm install axios

Example

jsx

import { useState, useEffect } from "react";
import axios from "axios";

function CourseList() {
  const [courses, setCourses] = useState([]);

  useEffect(() => {
    async function loadCourses() {
      const response = await axios.get("https://jsonplaceholder.typicode.com/posts");
      setCourses(response.data);
    }

    loadCourses();
  }, []);

  return (
    <ul>
      {courses.slice(0, 5).map(course => (
        <li key={course.id}>{course.title}</li>
      ))}
    </ul>
  );
}

export default CourseList;

fetch vs Axios

Aspect

fetch()

Axios

InstallationBuilt into browsersnpm install axios
JSON parsingManual: await response.json()Automatic: response.data
HTTP error status (404, 500)Does not throw; check response.okThrows automatically
Request timeoutManual setup requiredBuilt-in option
Sending JSONSet headers and JSON.stringify() manuallyHandled for you
Bundle sizeNoneSmall, but non-zero

Which Should You Use?

Either is fine. fetch() is built in and adds nothing to your bundle. Axios reduces boilerplate, especially in apps making many requests with shared headers such as authentication tokens.

The one trap worth remembering: fetch() does not throw on a 404 or 500 response. It only throws on network failure. You must check response.ok yourself, as shown in the useFetch Hook in Module 7.


ReactJS Tutorial

VA

Vishalini A



Learn via Video Course

React.js for Beginners: Build Modern Web Applications with React Logo

React.js for Beginners: Build Modern Web Applications with React

6 hrs



Get in Touch For Details