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
// Filename - App.js
import { useEffect } from "react";
function App() {
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/todos')
.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
// Filename - App.js
import { useEffect } from "react";
import axios from "axios"
function App() {
useEffect(() => {
axios.get("https://jsonplaceholder.typicode.com/todos")
.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
// Filename - App.js
import { useEffect } from "react";
import axios from "axios"
function App() {
useEffect(() => {
(async () => {
try {
const result = await axios.get(
"https://jsonplaceholder.typicode.com/todos")
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
// Filename - App.js
import { useEffect } from "react";
import useFetch from "useFetch.js";
function App() {
const { data: dataInfo, loading, error, refetch } = useFetch(
https://jsonplaceholder.typicode.com/todos
);
return (
<div >
Different ways to fetch data
{console.log(data)}
</div>
);
}
export default App;
JavaScript
//Filename - useFetch.js
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
8 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
Different ways to access props inside a Component in React
The props keyword is the shorthand for properties. It is one of the most important features of React which helps in effective communication between various React components. It is a read-only attribute for passing data from the parent component to the child component. There are various ways to acces
4 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
Different Ways To Render a List of Items in React
In React, when we are working with dynamic data, it is common to render a list of items. In React, there are several methods to render the list efficiently.1. Using Array.map()Array.map() is an inbuilt JavaScript function provided by JavaScript. It iterates over the list of items in the array and re
5 min read
How to create a Location finder app using ReactJS ?
In this article, we will be building a location finder app that lets you search for different places on a map. Our app contains two sections, one for displaying the marker on the map and the other is for searching different places. For rendering the map and getting the coordinates for the searched l
4 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
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
9 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 h
4 min read