Loading and Error States in React
In this lesson, you will learn how to manage loading, success, empty, and error states while fetching API data. You will use React's useState and useEffect Hooks to provide clear feedback to users during asynchronous operations.
1. What Are Loading and Error States?
When a React application requests data from an API, the request does not always finish immediately. It may take time to receive the response, return an empty result, or fail because of a network problem or an unsuccessful HTTP status.
Loading and error states help the application communicate what is happening instead of showing a blank page or leaving the user wondering whether the application is working.
Common UI States
- Loading: The request is in progress.
- Success: The request succeeded and data is available.
- Empty: The request succeeded, but there are no records to display.
- Error: The request failed or the response could not be processed.
2. Understanding the Request Flow
The component starts in a loading state. When the request completes, the application updates its state and renders the appropriate message or data.
3. Create State Variables
React's useState Hook allows a component to store
values that change over time. For an API request, we commonly
maintain three pieces of state: the returned data, the loading
status, and an error message.
import { useState } from "react";
function Users() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
return (
<div>
<h2>Users List</h2>
</div>
);
}
export default Users;
Explanation
usersstores the API records.loadingindicates whether the request is in progress.errorstores an error message when the request fails.setUsers,setLoading, andsetErrorupdate their respective states.
4. Display a Loading Message
While the API request is running, display a message so the user knows that data is being retrieved.
{loading && <p>Loading users...</p>}
The && operator is used here for conditional
rendering. The paragraph appears only when loading
is true.
Example Output
Loading users...
When the request finishes and the loading state becomes false, this loading message is no longer displayed.
5. Handle API Errors
API requests can fail because of network issues, server problems, or unsuccessful HTTP responses. Use a try/catch block to handle rejected requests and explicitly throw an error when the HTTP response is unsuccessful.
async function fetchUsers() {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users"
);
if (!response.ok) {
throw new Error("Unable to load users");
}
const data = await response.json();
setUsers(data);
} catch (err) {
setError(err.message || "Something went wrong");
} finally {
setLoading(false);
}
}
Understanding the Code
trycontains the code that may fail.response.okchecks whether the HTTP status is successful.throw new Error()creates an error for an unsuccessful HTTP response.catchstores the error message in state.finallyruns whether the try block succeeds or fails.setLoading(false)ends the loading state.
response.ok
is important when those responses should be treated as errors.
6. Display the Error Message
After storing an error message, display it in the interface so the user can understand that the request did not succeed.
{error && <p role="alert">Error: {error}</p>}
Example Output
Error: Unable to load users
The role="alert" attribute helps assistive technologies
identify important feedback. Keep error messages understandable
and avoid exposing sensitive technical details.
7. Complete React Example
The following component combines loading, success, empty, and error states in one example. It fetches user data, checks the response, and renders the appropriate interface.
import { useEffect, useState } from "react";
function Users() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
const controller = new AbortController();
async function fetchUsers() {
try {
setLoading(true);
setError("");
const response = await fetch(
"https://jsonplaceholder.typicode.com/users",
{ signal: controller.signal }
);
if (!response.ok) {
throw new Error("Failed to load users");
}
const data = await response.json();
setUsers(data);
} catch (err) {
if (err.name !== "AbortError") {
setError(err.message || "Something went wrong");
}
} finally {
if (!controller.signal.aborted) {
setLoading(false);
}
}
}
fetchUsers();
return () => {
controller.abort();
};
}, []);
if (loading) {
return <p>Loading users...</p>;
}
if (error) {
return <p role="alert">Error: {error}</p>;
}
if (users.length === 0) {
return <p>No users available.</p>;
}
return (
<div>
<h2>Users List</h2>
<ul>
{users.map(user => (
<li key={user.id}>
<strong>{user.name}</strong>
{" - "}
{user.email}
</li>
))}
</ul>
</div>
);
}
export default Users;
Step-by-Step Explanation
useStatestores the records, loading status, and error message.useEffectstarts the API request when the component mounts.AbortControllerallows the request to be cancelled during cleanup.- The request begins with loading enabled and the previous error cleared.
- The response is checked before its JSON body is parsed.
- Successful data is stored using
setUsers(data). - Errors are stored in state, except for an intentional request cancellation.
- The finally block ends loading unless the request was aborted.
- Conditional returns render loading, error, empty, or success UI.
8. Expected UI States
Loading State
Loading users...
The application is waiting for the API response.
Success State
Samadhan - samadhan@example.com
Samiksha - samiksha@example.com
The application received records and displayed them.
Empty State
No users available.
The request succeeded, but the returned array contains no records.
Error State
Error: Failed to load users
The request failed or the response could not be processed.
9. Common Mistakes
- Never ending loading: Set loading to false after both success and failure, typically with finally.
-
Ignoring HTTP errors: Check
response.okbecause Fetch does not reject automatically for 404 or 500 responses. - Showing an error for empty data: An empty array can be a valid successful result.
- Updating state after cancellation: Use AbortController where appropriate and ignore abort errors.
- Displaying unclear error messages: Tell users what happened without revealing sensitive server details.
- Showing multiple states simultaneously: Use an intentional order for loading, error, empty, and success rendering.
10. Practice Tasks
Task 1: Add a Loading Message
Fetch users from
https://jsonplaceholder.typicode.com/users
and display "Loading users..." while the request is in progress.
Task 2: Handle Failed Responses
Check response.ok and display an error message
when the server returns an unsuccessful HTTP status.
Task 3: Display an Empty State
Display "No records available" when the API returns an empty array after a successful request.
Task 4: Add Request Cleanup
Use AbortController to cancel the Fetch request when the component's Effect is cleaned up.
Task 5: Create a Posts Component
Fetch posts from
https://jsonplaceholder.typicode.com/posts
and implement loading, error, empty, and success states.
Summary
In this lesson, you learned how to manage loading, success, empty, and error states while working with APIs in React. You used useState to store data and status messages, useEffect to start the request, async and await to handle asynchronous operations, try/catch/finally for error handling, and AbortController for request cancellation. In the next lesson, you will learn how to send POST requests from React to submit data to an API.