Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
How to create a Dictionary App in ReactJS ?
Next article icon

How to Fetch Data From an API in ReactJS?

Last Updated : 19 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

ReactJS provides several ways to interact with APIs, allowing you to retrieve data from the server and display it in your application. In this article, we’ll walk you through different methods to fetch data from an API in ReactJS, including using the built-in fetch method, axios, and managing the state effectively.

1. Using JavaScript fetch() method

The fetch() method in JavaScript is used to make network requests (such as HTTP requests) and fetch data from a specified URL. It returns a Promise that resolves to the Response object representing the response to the request.

CSS
/* App.css*/  .App {     text-align: center;     /* color: Green; */ } .container {     display: flex;     flex-direction: row;     flex-wrap: wrap;     justify-content: center; }  .item {     min-width: 33rem;     text-align: left; }  .geeks {     color: green; } 
JavaScript
import React, { useState, useEffect } from "react"; import "./App.css";  const App = () => {     const [items, setItems] = useState([]);     const [dataIsLoaded, setDataIsLoaded] = useState(false);      useEffect(() => {         fetch("https://jsonplaceholder.typicode.com/users")             .then((res) => res.json())             .then((json) => {                 setItems(json);                 setDataIsLoaded(true);             });     }, []);       if (!dataIsLoaded) {         return (             <div>                 <h1>Please wait some time....</h1>             </div>         );     }      return (         <div className="App">             <h1 className="geeks">GeeksforGeeks</h1>             <h3>Fetch data from an API in React</h3>             <div className="container">                 {items.map((item) => (                     <div className="item" key={item.id}>                         <ol>                             <div>                                 <strong>User_Name: </strong>                                 {item.username},                             </div>                             <div>Full_Name: {item.name}</div>                             <div>User_Email: {item.email}</div>                         </ol>                     </div>                 ))}             </div>         </div>     ); };  export default App; 

OutputPeek-2023-10-05-17-33

In this example

  • This React component fetches data from an API using the fetch method inside componentDidMount().
  • It stores the fetched data in the state and displays the user’s username, name, and email once the data is loaded.
  • If the data is still loading, it shows a “Please wait” message.

2. Using axios library

Axios library is a popular, promise-based JavaScript library used to make HTTP requests from the browser or NodeJS. It simplifies making requests to APIs, handling responses, and managing errors compared to the native fetch() method.

Install Axios library using the following command

npm i axios

The updated dependencies in the package.json file are:

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"axios": "^1.5.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
CSS
/* App.css*/  .App {     text-align: center;     /* color: Green; */ } .container {     display: flex;     flex-direction: row;     flex-wrap: wrap;     justify-content: center; }  .item {     min-width: 33rem;     text-align: left; }  .geeks {     color: green; } 
JavaScript
// App.js import React, { useState, useEffect } from "react"; import "./App.css"; import axios from "axios";  const App = () => {     const [items, setItems] = useState([]);     const [dataIsLoaded, setDataIsLoaded] = useState(false);      useEffect(() => {         axios             .get("https://jsonplaceholder.typicode.com/users")             .then((res) => {                 setItems(res.data);                 setDataIsLoaded(true);             });     }, []);      if (!dataIsLoaded) {         return (             <div>                 <h1>Please wait some time....</h1>             </div>         );     }      return (         <div className="App">             <h1 className="geeks">GeeksforGeeks</h1>             <h3>Fetch data from an API in React</h3>             <div className="container">                 {items.map((item) => (                     <div className="item" key={item.id}>                         <ol>                             <div>                                 <strong>User_Name: </strong>                                 {item.username},                             </div>                             <div>Full_Name: {item.name}</div>                             <div>User_Email: {item.email}</div>                         </ol>                     </div>                 ))}             </div>         </div>     ); };  export default App; 

Output

Peek-2023-10-05-17-33

In this code

  • This React component uses Axios to fetch data from an API when the component mounts.
  • It stores the fetched data in the state and displays the users’ username, name, and email once the data is loaded.
  • If the data is not loaded, it shows a loading message.

3. Using the Stale-While-Revalidate (SWR) Method

SWR is a data-fetching library developed by Vercel that makes it easy to fetch and cache data in React applications. The concept behind SWR is simple: fetch data, use stale data for immediate UI rendering, and revalidate it in the background to get fresh data.

Steps to Install SWR

npm install swr
JavaScript
import React from 'react'; import useSWR from 'swr';  const fetcher = (url) => fetch(url).then((res) => res.json());  const App = () => {     const { data, error } = useSWR('https://jsonplaceholder.typicode.com/users', fetcher);      if (error) return <p>Error loading data</p>;     if (!data) return <p>Loading...</p>;      return (         <div>             <ul>                 {data.map((user) => (                     <li key={user.id}>                         <h3>{user.username}</h3>                         <p>{user.name}</p>                         <p>{user.email}</p>                     </li>                 ))}             </ul>         </div>     ); };  export default App; 

Output

SWR-1

Fetch Data From an API in ReactJS

In this code

  • SWR automatically handles caching, background revalidation, and state management for data fetching.
  • The useSWR hook fetches the data and handles the logic for loading, error, and success states.
  • It provides an automatic re-fetching of data if the component re-renders or if the data becomes stale.

4. Using the React Query Library

React Query is another powerful library that simplifies data fetching, caching, synchronization, and more. It is great for applications where the data changes frequently and you need efficient, real-time data fetching with minimal boilerplate.

Steps to Install React Query

npm install react-query
App.js
import React from 'react'; import { useQuery } from 'react-query';  // Function to fetch data const fetchUsers = async () => {     const res = await fetch('https://jsonplaceholder.typicode.com/users');     if (!res.ok) throw new Error('Network error');     return res.json(); };  const App = () => {     // Use useQuery to fetch data     const { data, error, isLoading } = useQuery('users', fetchUsers);      if (isLoading) return <p>Loading...</p>;     if (error) return <p>Error loading data</p>;      return (         <div>             <h1>User List</h1>             <ul>                 {data.map((user) => (                     <li key={user.id}>                         <h3>{user.username}</h3>                         <p>{user.name}</p>                         <p>{user.email}</p>                     </li>                 ))}             </ul>         </div>     ); };  export default App; 
QueryClient.js
import React from 'react'; import { QueryClient, QueryClientProvider } from 'react-query'; import App from './App';  const queryClient = new QueryClient();  function Root() {     return (         <QueryClientProvider client={queryClient}>             <App />         </QueryClientProvider>     ); }  export default Root; 

Output

SWR-4

Fetch Data From an API in ReactJS

In this code

  • React Query’s useQuery hook is used to fetch data and manage state.
  • It automatically handles caching, background refetching, and error handling.
  • If the data is still loading, it shows a loading message. If there’s an error, it displays an error message.

Conclusion

Fetching data from an API is a critical task in modern web applications, and both fetch() and Axios are widely used methods for achieving this in React. Use fetch() if you prefer a native, lightweight solution for making HTTP requests in your React apps. Use Axios for more features like automatic JSON parsing, improved error handling, and a cleaner syntax for HTTP requests.



Next Article
How to create a Dictionary App in ReactJS ?
author
nishantsinghgfg
Improve
Article Tags :
  • ReactJS
  • Web Technologies
  • React-Questions

Similar Reads

  • How To Fetch Data From APIs In NextJS?
    Fetching data from APIs in Next.js can be done using built-in methods like getServerSideProps, getStaticProps, or client-side fetching with useEffect. This flexibility supports both server-side and static data fetching. Prerequisites:NPM & NodeJSReactJSReact HooksReact RouterApproachTo fetch dat
    2 min read
  • How to fetch data from APIs using Asynchronous await in ReactJS ?
    Fetching data from an API in ReactJS is a common and crucial task in modern web development. Fetching data from API helps in getting real-time updates dynamically and efficiently. API provides on-demand data as required rather than loading all data. PrerequisitesReact JSFetch data from APIApproachTo
    3 min read
  • How to get complete cache data in ReactJS?
    In React, we can get all cache data from the browser and use it in our application whenever needed. Caching is a technique that helps us to store a copy of a given resource in our browser and serve it back when requested. PrerequisitesReact JSCacheStorageApproachTo get all cache data in React JS def
    2 min read
  • How to create a form in React?
    React uses forms to allow users to interact with the web page. In React, form data is usually handled by the components. When the data is handled by the components, all the data is stored in the component state. You can control changes by adding event handlers in the onChange attribute and that even
    5 min read
  • How to create a Dictionary App in ReactJS ?
    In this article, we will be building a very simple Dictionary app with the help of an API. This is a perfect project for beginners as it will teach you how to fetch information from an API and display it and some basics of how React actually works. Also, we will learn about how to use React icons. L
    4 min read
  • How to fetch data from a local JSON file in React Native ?
    Fetching JSON (JavaScript Object Notation) data in React Native from Local (E.g. IOS/Android storage) is different from fetching JSON data from a server (using Fetch or Axios). It requires Storage permission for APP and a Library to provide Native filesystem access. Implementation: Now let’s start w
    4 min read
  • How to Create RESTful API and Fetch Data using ReactJS ?
    React JS is more than just an open-source JavaScript library, it's a powerful tool for crafting user interfaces with unparalleled efficiency and clarity. One of React's core principles is its component-based architecture, which aligns perfectly with the Model View Controller (MVC) pattern. React com
    5 min read
  • How to get single cache data in ReactJS ?
    We can use cache storage using window cache and in React JS to get single cache data. We can get single cache data from the browser and use it in our application whenever needed. Caching is a technique that helps us to store a copy of a given resource in our browser and serve it back when requested.
    2 min read
  • How to use Firestore Database in ReactJS ?
    Firebase is a comprehensive backend solution offered by Google that simplifies the process of building, managing, and growing applications. When developing mobile or web apps, handling the database, hosting, and authentication can be challenging tasks. Firebase addresses these challenges by providin
    10 min read
  • How to get multiple cache data in ReactJS ?
    We can use the following approach in ReactJS to get multiple cache data. We can get multiple cache data from the browser and use them in our application whenever needed. Caching is a technique that helps us to store a copy of a given resource in our browser and serve it back when requested. Prerequi
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences