Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet HTML/CSS Java JavaScript Node.js Python Python 3.11, Pandas, SQL
      Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. React
  4. Fetching Data with Axios in React: A Comprehensive Guide

Fetching Data with Axios in React: A Comprehensive Guide

Date- Apr 03,2026 2
axios react

Overview

Data fetching is a fundamental aspect of modern web applications, enabling developers to retrieve and display data from various sources like RESTful APIs, GraphQL endpoints, and other web services. Axios is a widely-used library that simplifies the process of making HTTP requests in JavaScript, providing a rich set of features such as interceptors, request cancellation, and automatic JSON data transformation. The need for efficient data fetching arises from the necessity to keep applications responsive and up-to-date with real-time data, especially in scenarios such as social media feeds, e-commerce product listings, and dashboards.

In real-world applications, developers often face challenges when it comes to handling asynchronous operations, managing loading states, and error handling. Axios addresses these challenges by providing a straightforward API, making it easier to integrate with React components. This guide will walk through the essentials of using Axios within a React application, covering various scenarios, pitfalls, and best practices.

Prerequisites

  • Basic React Knowledge: Familiarity with React components, hooks, and state management.
  • JavaScript ES6: Understanding of Promises, async/await syntax, and arrow functions.
  • Node.js and npm: Installed on your machine for managing packages.
  • Axios Library: Basic knowledge of how to install and import libraries in a React project.

Setting Up Axios in Your React Project

Before you can use Axios, you need to install it in your React project. This can be done via npm or yarn. The installation step is critical as it allows you to leverage Axios's features in your application.

npm install axios

After installation, you can import Axios into your component files. This import statement gives you access to the Axios instance and its methods.

import axios from 'axios';

By importing Axios, you can now use its methods to make HTTP requests, manage responses, and handle errors efficiently.

Basic GET Request

To demonstrate how Axios works, let's create a simple GET request to fetch user data from a public API. The following example fetches user data from the JSONPlaceholder API.

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

const UserList = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    const fetchUsers = async () => {
      try {
        const response = await axios.get('https://jsonplaceholder.typicode.com/users');
        setUsers(response.data);
      } catch (err) {
        setError('Failed to fetch users.');
      } finally {
        setLoading(false);
      }
    };
    fetchUsers();
  }, []);

  if (loading) return 

Loading...

; if (error) return

{error}

; return (
    {users.map(user => (
  • {user.name}
  • ))}
); }; export default UserList;

This code defines a functional component called UserList. It uses the useState hook to manage users, loading, and error states. The useEffect hook runs when the component mounts, triggering the fetchUsers function.

Inside fetchUsers, a GET request is made to the JSONPlaceholder API using axios.get. If the request is successful, the user data is stored in the users state. If an error occurs, the error state is updated with a message. The loading state is managed to show a loading message while the data is being fetched.

The expected output is a list of user names displayed on the screen, or an error message if the fetching fails.

Handling POST Requests

In addition to GET requests, Axios can also handle POST requests, which are commonly used to send data to a server. This is useful when creating new resources in applications, such as submitting a form.

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

const CreateUser = () => {
  const [name, setName] = useState('');
  const [message, setMessage] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const response = await axios.post('https://jsonplaceholder.typicode.com/users', { name });
      setMessage(`User ${response.data.name} created!`);
    } catch (err) {
      setMessage('Error creating user.');
    }
  };

  return (
    
setName(e.target.value)} placeholder="Enter name" /> {message &&

{message}

}
); }; export default CreateUser;

The CreateUser component uses the useState hook to manage name and message states. The handleSubmit function is triggered when the form is submitted. It prevents the default form submission behavior and makes a POST request to the API with the new user's name.

If the request succeeds, a success message is set, otherwise, an error message is displayed. This component showcases how to send data to an API and handle responses effectively.

Error Handling in Axios

Robust error handling is crucial for any application that communicates over the network. Axios provides several ways to handle errors that may arise during requests. Understanding how to effectively manage these errors can significantly enhance user experience.

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

const ErrorHandlingExample = () => {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('https://jsonplaceholder.typicode.com/invalid-url');
        setData(response.data);
      } catch (err) {
        setError(err.response ? err.response.data : 'Network Error');
      }
    };
    fetchData();
  }, []);

  return (
    
{error ?

Error: {error}

:

Data: {data}

}
); }; export default ErrorHandlingExample;

This example demonstrates how to set an error state when a request fails. The fetchData function attempts to fetch data from an invalid URL, which triggers the catch block. The error message is set based on whether the error response is available or if it's a network error.

User feedback is crucial during errors, and this simple mechanism helps provide clarity on what went wrong, allowing for better troubleshooting.

Interceptors for Request and Response

Axios interceptors can be used to run your code or modify requests and responses before they are handled by then or catch. This feature is particularly useful for adding authorization tokens, logging requests, or handling global error responses.

import axios from 'axios';

axios.interceptors.request.use(config => {
  config.headers['Authorization'] = 'Bearer YOUR_TOKEN';
  return config;
}, error => {
  return Promise.reject(error);
});

axios.interceptors.response.use(response => {
  return response;
}, error => {
  console.error('Global error handler:', error);
  return Promise.reject(error);
});

The request interceptor in the example adds an Authorization header to all outgoing requests, which is essential for APIs requiring authentication. The response interceptor logs errors globally, providing a centralized way to handle issues across the application.

Using Interceptors with React Components

Integrating interceptors with React components allows seamless handling of requests without cluttering individual components. This can enhance maintainability and reduce redundancy across your codebase.

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

const InterceptorExample = () => {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('https://jsonplaceholder.typicode.com/users');
        setData(response.data);
      } catch (err) {
        setError(err.message);
      }
    };
    fetchData();
  }, []);

  return (
    
{error ?

Error: {error}

:
    {data && data.map(user =>
  • {user.name}
  • )}
}
); }; export default InterceptorExample;

This example demonstrates a component that utilizes Axios interceptors. If an error occurs during the request, the error state is updated, allowing the component to display an error message to the user. This approach ensures that all components benefit from the centralized interceptors without repeating code.

Edge Cases & Gotchas

When working with Axios in React, it's important to be aware of certain edge cases and pitfalls that can lead to unexpected behavior or bugs. Understanding these gotchas can help avoid common mistakes and improve the reliability of your application.

Memory Leaks in Component Unmounting

One common issue arises when a component that makes an Axios request unmounts before the request resolves. This can lead to memory leaks or attempts to update the state of an unmounted component.

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

const SafeFetch = () => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let isMounted = true;
    const fetchData = async () => {
      const response = await axios.get('https://jsonplaceholder.typicode.com/users');
      if (isMounted) {
        setData(response.data);
        setLoading(false);
      }
    };
    fetchData();
    return () => { isMounted = false; };
  }, []);

  if (loading) return 

Loading...

; return
    {data.map(user =>
  • {user.name}
  • )}
; }; export default SafeFetch;

In this example, a flag isMounted is used to track whether the component is still mounted when the request resolves. This prevents attempts to call setData and setLoading on an unmounted component, avoiding potential memory leaks.

Handling Cancelled Requests

When making requests that can be cancelled, such as when a user navigates away from a page, it's crucial to handle cancellation properly to prevent unnecessary state updates.

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

const CancelRequestExample = () => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const source = axios.CancelToken.source();
    const fetchData = async () => {
      try {
        const response = await axios.get('https://jsonplaceholder.typicode.com/users', {
          cancelToken: source.token
        });
        setData(response.data);
      } catch (err) {
        if (axios.isCancel(err)) {
          console.log('Request cancelled:', err.message);
        } else {
          console.error('Error:', err);
        }
      } finally {
        setLoading(false);
      }
    };
    fetchData();
    return () => { source.cancel('Operation cancelled by the user.'); };
  }, []);

  if (loading) return 

Loading...

; return
    {data.map(user =>
  • {user.name}
  • )}
; }; export default CancelRequestExample;

This example shows how to use a cancel token with Axios. The request can be cancelled when the component unmounts, preventing state updates if the request is still pending. This approach enhances performance and user experience by ensuring that unnecessary operations are not performed.

Performance & Best Practices

When working with Axios in React, it is essential to follow best practices to ensure optimal performance and maintainability. These best practices include managing state efficiently, structuring your components, and optimizing your requests.

Using Custom Hooks for Data Fetching

Creating custom hooks for data fetching can help encapsulate the logic and make your components cleaner and more reusable. This approach allows you to isolate the fetching logic from the UI logic.

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

const useFetch = (url) => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get(url);
        setData(response.data);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, [url]);

  return { data, loading, error };
};

export default useFetch;

This custom hook, useFetch, can be used in any component to fetch data by simply passing the URL. It returns the fetched data, loading state, and error state, promoting reusability and cleaner component code.

Throttling and Debouncing Requests

When dealing with user input that triggers requests, such as search fields, it's essential to throttle or debounce requests to avoid overwhelming the server with too many requests.

import React, { useState } from 'react';
import axios from 'axios';
import { debounce } from 'lodash';

const SearchComponent = () => {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState([]);

  const fetchResults = debounce(async (searchQuery) => {
    const response = await axios.get(`https://api.example.com/search?query=${searchQuery}`);
    setResults(response.data);
  }, 500);

  const handleChange = (e) => {
    const value = e.target.value;
    setQuery(value);
    fetchResults(value);
  };

  return (
    
    {results.map(result =>
  • {result.name}
  • )}
); }; export default SearchComponent;

This SearchComponent uses lodash's debounce function to limit the number of requests made as the user types. This not only improves performance but also enhances user experience by preventing lag and providing timely results.

Real-World Scenario: Building a User Dashboard

Combining all the concepts discussed, let's create a mini-project that fetches user data and displays it in a simple dashboard format. This project will utilize Axios for fetching data and demonstrate best practices discussed earlier.

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

const UserDashboard = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    const fetchUsers = async () => {
      try {
        const response = await axios.get('https://jsonplaceholder.typicode.com/users');
        setUsers(response.data);
      } catch (err) {
        setError('Unable to fetch users.');
      } finally {
        setLoading(false);
      }
    };
    fetchUsers();
  }, []);

  return (
    

User Dashboard

{loading &&

Loading...

} {error &&

{error}

}
    {users.map(user => (
  • {user.name} - {user.email}
  • ))}
); }; export default UserDashboard;

This UserDashboard component fetches a list of users and displays their names and email addresses. It incorporates loading and error states to enhance user experience. This complete example ties together all the concepts of data fetching with Axios in a real-world scenario.

Conclusion

  • Axios simplifies making HTTP requests in React applications.
  • Custom hooks can encapsulate data fetching logic, improving code organization.
  • Error handling is crucial for robust applications; utilize Axios's built-in mechanisms.
  • Interceptors can help manage requests and responses globally.
  • Performance can be enhanced through debouncing and throttling of requests.

Next, consider exploring state management solutions like Redux or Context API to manage global state in conjunction with data fetching.

S
Shubham Saini
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Mastering Navigation in React with React Router
Apr 02, 2026
Deep Dive into React Components: Understanding Functional and Class Components
Apr 02, 2026
Mastering React: A Comprehensive Guide to Getting Started
Apr 02, 2026
Mastering JavaScript Error Handling with Try, Catch, and Finally
Mar 31, 2026
Previous in React
Mastering Redux with React: A Comprehensive Guide for Developers
Next in React
Mastering React Performance Optimization: A Deep Dive into useMem…
Buy me a pizza

Comments

On this page

🎯

Interview Prep

Ace your React interview with curated Q&As for all levels.

View React Interview Q&As

More in React

  • Mastering React Context API for Effective State Management 32 views
  • Mastering Forms and Controlled Components in React: A Deep D… 11 views
  • Understanding Props and State in React: A Comprehensive Guid… 10 views
  • Mastering React Hooks: A Deep Dive into useState, useEffect,… 9 views
  • Mastering Redux with React: A Comprehensive Guide for Develo… 2 views
View all React posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • HTML/CSS
  • Java
  • JavaScript
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor