How to create a component to fetch data from an API in React?
Learn to fetch and display data using useEffect and fetch API with proper loading and error handling.
intermediateData fetchingreactapiuseEffectfetch
Published: 10/26/2025
Updated: 10/26/2025
Question
How to create a component to fetch data from an API in React?
Answer
Use useEffect for side effects and fetch() or axios to retrieve data.
import { useEffect, useState } from 'react';
function UserList() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchData() {
const res = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await res.json();
setUsers(data);
setLoading(false);
}
fetchData();
}, []);
if (loading) return <p>Loading...</p>;
return (
<ul>
{users.map((u) => (
<li key={u.id}>{u.name}</li>
))}
</ul>
);
}
âś… Always handle loading state to improve UX.
Real-World Example
Fetching data for:
- Dashboards
- Lists and tables
- Infinite scrolls
Quick Practice
Build a “Job List” component fetching job titles from an API endpoint and display them dynamically.
Summary
Use useEffect + async fetch to call APIs, manage loading state, and render responses cleanly.
Related Videos
Watch these videos to learn more about this topic
Frequently Asked Questions
Can I use async directly inside useEffect?
Not directly. Wrap it in an async function inside the effect.
Stay Updated
Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.