How to Fetch Data From an API in ReactJS?
Last Updated :
23 Jul, 2025
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.
Prerequisites:
- Node.js should be installed
- You should have a basic understanding of React.js
- A text Editor (Such as VS Code, etc.)
API(Application Programming Interface)First of all, we need to understand about API(Application Programming Interface) - It enables the exchange of Information and functionality between different systems, such as between website or server or between different software applications.
Now, we’ll look at the various methods available for fetching data from an API in ReactJS:
Method 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.
App.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;
}
App.js
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;
Output
OutputCode Overview:
- 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.
Method 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
bash
The updated dependencies in the package.json file are:
bash
"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.6.7",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
Note: The version number may differ slightly depending on the latest release. As of early 2025, version 1.6.x
is common.
App.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;
}
App.js
// 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:
output
Code Overview:
- 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.
Method 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. SWR includes useState() and useEffect(), so there is no need to import them.
Below we have mentioned Steps to Install SWR
Step1 : Install swr
bash
Step 2: Import all the packages needed for the App.
App.js
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
OutputCode Overview:
- 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.
Method 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
bash
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
OutputCode Overview:
- 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.
Method 5. Use the useFetch
custom hook from react-fetch-hook
A custom hook in React is a regular Javascript function that lets you reuse logic across different components. It's built using React's built-in hooks like useState and useEffect.
Custom hooks make your code cleaner and easier to manage by putting shared functionality in one place. For example:- if you fetch data in several components, you can write a custom hook like useFetch
to handle it.
Step 1: Install the react-fetch-hook
bash
npm install react-fetch-hook
Once the installation is complete, navigate to the start of your application's file
Step 2: Import the package for React App file.
bash
import useFetch from "react-fetch-hook";
Syntax Example for react-fetch-hook
App.js
import React from 'react';
import useFetch from 'react-fetch-hook';
function App() {
const { isLoading, data, error } = useFetch("https://jsonplaceholder.typicode.com/posts");
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div style={{ padding: "20px", fontFamily: "Arial" }}>
<h1>Posts</h1>
<ul>
{data.slice(0, 10).map((post) => (
<li key={post.id}>
<strong>{post.title}</strong>
<p>{post.body}</p>
</li>
))}
</ul>
</div>
);
}
export default App;
Each Method has it's own strength but choosing the Best API Method in React is essential while Fetching Data from an API.
- fetch() : It is Lightweight and built into JavaScript, making it perfect for simple and small-scale projects without adding dependencies.
- axios: It Provides a cleaner API, automatic JSON parsing, better error handling, and supports features like interceptors for robust HTTP requests.
- SWR: It automatically handles caching, revalidation, and background data fetching with minimal code, ideal for real-time and performance-focused apps.
- React Query: It is an Advanced server-state management with powerful caching, background refetching, and pagination support, best for complex and large-scale applications.
react-fetch-hook (useFetch): It Simplifies data fetching with an easy-to-use custom hook, making it great for developers who want minimal setup and a lightweight solution.
Summary
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.
Efficiency and Use Cases of API Fetching Methods in React
Fetching Method | Ideal Use Case | Strength | Drawbacks |
---|
fetch(Native) | Simple, lightweight applications | Built-in, no dependencies, good for quick prototyping | Requires manual JSON parsing and error handling |
---|
Axios | Medium to large-scale projects | Cleaner syntax, auto-parsing, request/response interceptors | Requires installing an external library |
---|
SWR | Real-time data or performance-sensitive apps | Auto-caching, background updates, minimal boilerplate | Less control over logic, smaller ecosystem |
---|
React Query | Complex, data-intensive, production-ready apps | Advanced caching, pagination, mutations, background refetching. | More configuration and steeper learning curve |
---|
react-fetch-hook | Small to mid-sized apps with shared data logic | Reusable hook, easy setup, minimal configuration | Limited to basic use cases, fewer customization options |
---|
How to fetch data from an API in ReactJS ?
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. Why Use React?Before React, web development faced issues like slow DOM updates and mes
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. It is a package in React that provides DOM-specific methods that can be used at the top level of a web app to enable an efficient wa
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.Stateless (before hooks)
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