Different ways to fetch data using API in React
Last Updated :
28 Feb, 2024
API: API is an abbreviation for Application Programming Interface which is a collection of communication protocols and subroutines used by various programs to communicate between them.
A programmer can make use of various API tools to make its program easier and simpler. Also, an API facilitates programmers with an efficient way to develop their software programs.
Different Ways to Fetch the Data using API in React:
There are 4 different ways to fetch the data using API in react. Below is the stepwise implementation . For the sample data, we have used the API endpoint from
http://jsonplaceholder.typicode.com/users
1. Fetch Data from API using fetch method:
The fetch() method in JavaScript is used to request to the server and load the information in the webpages. The request can be of any APIs that return the data of the format JSON or XML. This method returns a promise.
Javascript
import { useEffect } from "react" ;
function App() {
useEffect(() => {
.then(response => response.json())
.then(json => console.log(json))
}, []);
return (
<div>
Different ways to fetch Data
</div>
);
}
export default App;
|
Output: Now open localhost:300 and in the console, the data is fetched.

2. Fetch data using API using Axios Package:
Axios is a promise-based HTTP client designed for Node.js and browsers. With Axios, we can easily send asynchronous HTTP requests to REST APIs and perform create, read, update and delete operations. It is an open-source collaboration project hosted on Github. It can be imported in plain Javascript or with any library accordingly.Â
To install Axios write the following command:
npm i axios
Javascript
import { useEffect } from "react" ;
import axios from "axios"
function App() {
useEffect(() => {
.then((response) => console.log(response.data));
}, []);
return (
<div>
Different ways to fetch Data
</div>
);
}
export default App;
|
Output: Now open localhost:300 and in the console, the data is fetched.

3. Fetch data using API with Async-Await:
Async-Await is the preferred way of fetching the data from an API.
Async:
Async simply allows us to write promise-based code as if it was synchronous and it checks that we are not breaking the execution thread. It operates asynchronously via the event loop. Async functions will always return a value.
Await:
Await function is used to wait for the promise. It could be used within the async block only. It makes the code wait until the promise returns a result. It is used to prevent call-back hell and we can use it with Axios rather than the fetch method as Axios makes our code look cleaner and also makes it shorter(as we don’t need to convert to JSON format).
Javascript
import { useEffect } from "react" ;
import axios from "axios"
function App() {
useEffect(() => {
(async () => {
try {
const result = await axios.get(
console.log(result.data);
} catch (error) {
console.error(error);
}
})()
})
return (
<div >
Different ways to fetch Data
</div>
);
}
export default App;
|
Output: Now open localhost:300 and in the console, the data is fetched.

4. Using Custom hook:
Create one file(useFetch.js) for your custom hook which returns the state of important parameters like data, loading, and error. App.js file will import this hook
Import the useFetch hook and pass the URL of the API endpoint from where you want to fetch data.
App.js
Javascript
import { useEffect } from "react" ;
import useFetch from "useFetch.js" ;
function App() {
const { data: dataInfo, loading, error, refetch } = useFetch(
https:
);
return (
<div >
Different ways to fetch data
{console.log(data)}
</div>
);
}
export default App;
|
Javascript
import { useEffect, useState } from "react" ;
import axios from "axios" ;
function useFetch(url) {
const [data, setData] = useState( "" );
const [loading, setLoading] = useState( false );
const [error, setError] = useState( "" );
useEffect(() => {
setLoading( true );
axios
.get(url)
.then((response) => {
setData(response.data);
})
. catch ((err) => {
setError(err);
})
.finally(() => {
setLoading( false );
});
}, [url]);
const refetch = () => {
setLoading( true );
axios
.get(url)
.then((response) => {
setData(response.data);
})
. catch ((err) => {
setError(err);
})
.finally(() => {
setLoading( false );
});
};
return { data, loading, error, refetch };
}
export default useFetch;
|
Output: Now open localhost:300 and in the console, the data is fetched.

Similar Reads
How to fetch data from an API in ReactJS ?
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 st
5 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 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 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
Different ways to retrieve specific pieces of state using selectors
In Redux applications, selectors are functions that facilitate the retrieval of specific pieces of state from the Redux store. Selectors play a crucial role in decoupling components from the store's structure and improving performance by memoizing computed values. Let's explore two approaches to ret
4 min read
What are the advantages of using JSX in ReactJS ?
JavaScript XML or JSX is an extension of the JavaScript language syntax. The React library is an extension to write XML-like code for elements and components. JSX tags have a tag name, attributes, and children. Although JSX is not a necessity to write React applications, it is extremely beneficial a
2 min read
Create a Random Joke using React app through API
In this tutorial, we'll make a website that fetches data (joke) from an external API and displays it on the screen. We'll be using React completely to base this website. Each time we reload the page and click the button, a new joke fetched and rendered on the screen by React. As we are using React f
3 min read
Create a Stock Market Prediction App using React-Native
We'll walk through the process of building a Stock Market Prediction App using React Native. The app will allow users to input a stock symbol, fetch real-time stock data, and even predict the price for the next trading day. Let's dive into the details! Preview of final output: Let us have a look at
4 min read
How to Create a Basic Notes App using ReactJS ?
Creating a basic notes app using React JS is a better way to learn how to manage state, handle user input, and render components dynamically. In this article, we are going to learn how to create a basic notes app using React JS. A notes app is a digital application that allows users to create, manag
4 min read
How to use JavaScript Fetch API to Get Data?
An API is a set of rules, protocols, and tools that allows different software applications to communicate with each other. One of the popular ways to perform API requests in JavaScript is by using Fetch API. What is the Fetch API?The Fetch API is a built-in JavaScript feature that allows you to make
4 min read