Fetching Data from an API with useEffect and useState Hook
Last Updated :
28 Apr, 2025
In modern web development, integrating APIs to fetch data is a common task. In React applications, the useEffect and useState hooks provide powerful tools for managing asynchronous data fetching. Combining these hooks enables fetching data from APIs efficiently.
This article explores how to effectively utilize these hooks to fetch data from an API, focusing on the Random Data API for practical examples
useState Hook:
React useState Hook allows to store and access of the state in the functional components. State refers to data or properties that need to be stored in an application.
Syntax of useState Hook:
const [state, setState] = useState(initialState);
useEffect Hook:
React useEffect hook handles the effects of the dependency array. It is called every time any state if the dependency array is modified or updated.
Syntax of useEffect Hook:
useEffect(() => {
// Effect code here
return () => {
// Cleanup code here (optional)
};
}, [dependencies]);
Approach to Fetch Data from API:
- Initialize state variables using useState.
- Utilize useEffect to trigger data fetching.
- Handle API calls within the useEffect callback.
- Update state with fetched data.
Fetching Random User Data
In this example, we'll create a React component called RandomUserData that fetches random user data from the Random Data API. The component will utilize the useState and useEffect hooks to manage state and handle the data fetching process respectively. Once the data is fetched, it will be displayed on the screen.
- We import React, useState, and useEffect from the 'react' package.
- The RandomUserData functional component is created to encapsulate the logic for fetching and displaying random user data.
- We define a state variable userData using the useState hook, initialized to null as we initially don't have any user data.
- Within the useEffect hook, we perform a fetch request to the Random Data API endpoint that provides random user data.
- Upon receiving a response, we convert it to JSON format and update the userData state with the fetched data using the setUserData function.
- In the component's return statement, we conditionally render user information once it's available. This prevents errors due to accessing undefined data before the fetch completes.
Example: This example implements the above-mentioned approach
JavaScript
/* RandomUserData.js */
import React,
{
useState,
useEffect
} from 'react';
function RandomUserData() {
const [userData, setUserData] = useState(null);
useEffect(() => {
fetch('https://random-data-api.com/api/users/random_user')
.then(response => response.json())
.then(data => setUserData(data));
}, []);
return (
<div>
{userData && (
<div>
<h2>User Information</h2>
<p>
Name:
{userData.first_name}
{userData.last_name}
</p>
<p>
Email: {userData.email}
</p>
{/* Add more user data fields as needed */}
</div>
)}
</div>
);
}
export default RandomUserData;
Output:
Fetching Random User Data OutputFetching Random User Data List
In this example, we'll create a React component called RandomUserList that fetches a list of random users from the Random Data API. The component will utilize the useState and useEffect hooks to manage state and handle the data fetching process respectively. Once the data is fetched, it will be displayed on the screen as a list of users.
- The RandomUserList component is created as a functional component to encapsulate the logic for fetching and displaying random user data.
- We define a state variable userList using the useState hook, initialized to an empty array as we initially don't have any user data.
- Within the useEffect hook, a fetch request is made to the Random Data API endpoint that provides a list of random users. We use the query parameter size=5 to specify that we want to fetch 5 random users.
- Upon receiving the response, we parse the JSON and update the userList state with the fetched user data using the setUserList function.
- In the component's return statement, we map through the userList array and display each user's information in a list format.
Example: This example implements the above-mentioned approach
JavaScript
/* RandomUserList.js */
import React,
{
useState,
useEffect
} from 'react';
function RandomUserList() {
const [userList, setUserList] = useState([]);
useEffect(() => {
fetch('https://random-data-api.com/api/v2/users?size=5')
.then(response => response.json())
.then(data => setUserList(data));
}, []);
return (
<div>
<h2>Random User List</h2>
<ul>
{userList.map(user => (
<li key={user.id}>
<p>
Name:
{user.first_name}
{user.last_name}
</p>
<p>
Email:
{user.email}
</p>
{/* Add more user data fields as needed */}
</li>
))}
</ul>
</div>
);
}
export default RandomUserList;
Output:
Fetching Random User Data List Output
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
Handling Error using React useState and useEffect Hooks In React, handling error states is very important to provide a smooth user experience and handle unexpected errors that may occur during data fetching or asynchronous operations. By using the useState and useEffect hooks, you can easily manage error states in your React applications. In this article
3 min read
What is useLayoutEffect, and how is it different from useEffect? `useLayoutEffect` runs synchronously right after all DOM changes, which makes it perfect for tasks that need access to the DOM before any visual updates occur, like measuring element size or position. On the other hand, `useEffect` runs asynchronously after the browser has finished painting changes,
2 min read
Difference Between useState and useEffect Hook in ReactJS ReactJS is the powerful JavaScript library used for building user interfaces especially single-page applications(SPAs). Two of the most commonly used hooks in React are useState and useEffect. These hooks make functional components more powerful by allowing them to manage the state and handle side e
3 min read
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 data
2 min read