Managing Loading States
What you'll learn: How to track and display loading indicators while your app fetches data from an API.
The Problem with Invisible Waiting
When you fetch data with useEffect, there's a gap between when the component mounts and when the data arrives. Without feedback, users see a blank screen and wonder if anything is happening. It's like calling a restaurant and hearing silence instead of "please hold" — uncomfortable and confusing.
The Loading State Pattern
Add a boolean state variable to track whether fetching is in progress:
function UserProfile() {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
setLoading(true); // Start loading
fetch('/api/user')
.then(response => response.json())
.then(data => {
setUser(data);
setLoading(false); // Done loading
});
}, []);
if (loading) {
return <div>Loading user data...</div>;
}
return <div>Welcome, {user.name}!</div>;
}
The Flow
- Initial state:
loadingstartstruebecause fetching begins immediately - During fetch: Show a spinner, skeleton, or "Loading..." message
- After fetch completes: Set
loadingtofalse, display the data
Conditional Rendering Based on Loading
Use the loading state to decide what UI to show:
if (loading)→ show spinner- Otherwise → show actual content
This prevents trying to access user.name when user is still null.
Key Takeaway: Always track loading state when fetching data — set it true before the fetch starts and false when it completes, then conditionally render your UI based on this state to provide clear user feedback.