We can use the useEffect hook to perform side effects like fetching data when the component mounts. useState is used to store the data and loading/error states.
✅ Example: Fetch Data from API
import React, { useState, useEffect } from "react";
const UsersList = () => {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchUsers = async () => {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
if (!response.ok) {
throw new Error("Network response was not ok");
}
const data = await response.json();
setUsers(data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
fetchUsers();
}, []); // Empty dependency array → runs once on mount
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
return (
<div>
<h2>Users List</h2>
<ul>
{users.map(user => (
<li key={user.id}>{user.name} ({user.email})</li>
))}
</ul>
</div>
);
};
export default UsersList;
🧩 Explanation:
useState→ to storeusers,loading, anderror.useEffect→ runs after the component mounts ([]dependency).- Async function inside useEffect → fetches data from API.
- Error handling → using
try/catch. - Conditional rendering → show loading or error messages.
- Display data → map through
usersand render list items.
✅ In short:
useEffectis perfect for fetching data when a component mounts, withuseStateto manage loading, error, and fetched data.