0
0
ReactComparisonBeginner · 4 min read

Fetch vs Axios in React: Key Differences and When to Use Each

In React, fetch is a built-in browser API for making HTTP requests, while axios is a popular third-party library that simplifies requests with extra features like automatic JSON parsing and better error handling. axios offers a cleaner syntax and more functionality out of the box, but fetch requires no installation and works well for simple requests.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of fetch and axios when used in React projects.

FeatureFetchAxios
InstallationBuilt-in browser API, no install neededRequires npm/yarn install
SyntaxUses Promises with then and catchSimpler syntax with automatic JSON parsing
Response ParsingManual response.json() call neededAutomatic JSON parsing of response data
Error HandlingOnly network errors reject; HTTP errors must be checked manuallyRejects on HTTP errors automatically
Request CancellationNo built-in supportSupports request cancellation with tokens
Browser SupportModern browsers only; needs polyfill for IESupports older browsers via polyfills
⚖️

Key Differences

fetch is a native browser API that returns a Promise and requires manual steps to parse JSON and handle HTTP errors. You must check response.ok to detect HTTP errors yourself, which can add extra code.

axios is a third-party library that wraps HTTP requests with a simpler API. It automatically parses JSON responses and rejects the Promise for HTTP error status codes, making error handling easier and cleaner.

Additionally, axios supports features like request cancellation, interceptors for modifying requests or responses, and automatic transformation of request data. fetch is more minimal and requires more manual work for these features.

⚖️

Code Comparison

This example shows how to fetch user data from an API using fetch in a React component.

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

function FetchExample() {
  const [user, setUser] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users/1')
      .then(response => {
        if (!response.ok) {
          throw new Error('HTTP error: ' + response.status);
        }
        return response.json();
      })
      .then(data => setUser(data))
      .catch(err => setError(err.message));
  }, []);

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

  return <div><h1>{user.name}</h1><p>{user.email}</p></div>;
}

export default FetchExample;
Output
<div><h1>Leanne Graham</h1><p>Sincere@april.biz</p></div>
↔️

Axios Equivalent

This example shows the same user data fetch using axios in React, which simplifies the code.

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

function AxiosExample() {
  const [user, setUser] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/users/1')
      .then(response => setUser(response.data))
      .catch(err => setError(err.message));
  }, []);

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

  return <div><h1>{user.name}</h1><p>{user.email}</p></div>;
}

export default AxiosExample;
Output
<div><h1>Leanne Graham</h1><p>Sincere@april.biz</p></div>
🎯

When to Use Which

Choose fetch when you want a simple, no-installation solution for basic HTTP requests and are comfortable handling JSON parsing and errors manually. It is great for small projects or when minimizing dependencies.

Choose axios when you need a cleaner syntax, automatic JSON handling, better error management, or advanced features like request cancellation and interceptors. It is ideal for larger React apps or when you want to write less boilerplate code.

Key Takeaways

Axios simplifies HTTP requests in React with automatic JSON parsing and better error handling.
Fetch is built-in and requires no installation but needs manual response parsing and error checks.
Use Axios for advanced features like request cancellation and interceptors.
Fetch is suitable for simple use cases or when avoiding extra dependencies.
Both can be used effectively in React depending on project needs and complexity.