The Classic useEffect Fetch Pattern
What you'll learn: How to fetch data from an API using the traditional pattern of useState for managing data/loading/error states and useEffect for performing the fetch operation.
The Core Pattern
When you need to load data from an API when a component mounts, the classic approach combines three pieces:
- Three state variables: one for the data itself, one for loading status, and one for any errors
- A
useEffecthook that runs the fetch operation - A dependency array that controls when the fetch happens
Think of it like ordering food delivery: you start with "loading" status, then either get your food (data) or receive an error message if something went wrong.
The Standard Recipe
function UserProfile({ userId }) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
setLoading(true);
fetch(`/api/users/${userId}`)
.then(response => response.json())
.then(result => {
setData(result);
setLoading(false);
})
.catch(err => {
setError(err.message);
setLoading(false);
});
}, [userId]); // Re-fetch when userId changes
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
return <div>{data.name}</div>;
}
The dependency array [userId] ensures the fetch runs again whenever userId changes, keeping your data synchronized with the props.
Why This Pattern Works
The useEffect runs after the component renders, preventing side effects during the render phase. The three-state approach gives you full control over UI feedback at every stage of the request lifecycle.
Key Takeaway: The classic fetch pattern uses three useState hooks (data, loading, error) inside a useEffect with proper dependencies to safely load and display asynchronous data.