| How to Organize API Calls in a React Application :👈 | 👉:How to Design Reusable React Components |
How to Handle Loading, Error, Empty, and Success States |
How to Handle Loading, Error, Empty, and Success States in React
1. Introduction
When building a React application, displaying data is not enough. We must also handle different situations that can occur while fetching or displaying data.
For example, imagine a React application that fetches a list of users from an API. The API request may have four possible outcomes:
- Loading: Data is still being fetched.
- Error: The API request failed.
- Empty: The request succeeded, but no records were returned.
- Success: The request succeeded and records are available.
Handling these states properly improves user experience and makes applications more reliable.
2. Understanding the Four States
2.1 Loading State
The loading state appears while the application is waiting for an API response.
function Users() {
const [loading, setLoading] = useState(true);
if (loading) {
return <p>Loading users...</p>;
}
return <div>User list</div>;
}
When to use:
- Fetching data from an API.
- Loading dashboard information.
- Submitting a form.
- Performing operations that take time.
You can display a spinner, skeleton screen, or loading message.
2.2 Error State
The error state appears when an API request fails or an unexpected problem occurs.
if (error) {
return <p>Something went wrong: {error}</p>;
}
Possible reasons include:
- Network connection problems.
- Server errors (500).
- Unauthorized requests (401).
- Resource not found (404).
- Invalid API responses.
A good error message should explain what happened and, when appropriate, provide a retry option.
2.3 Empty State
The empty state appears when the API request succeeds but returns no records.
if (users.length === 0) {
return <p>No users found.</p>;
}
An empty state is not an error.
For example, an API may successfully return:
[]
This means the request worked, but there are no users to display.
Useful empty-state messages include:
- No users available.
- No products found.
- No search results.
- No notifications yet.
For search interfaces, you can also suggest changing the search term or filters.
2.4 Success State
The success state appears when data is successfully fetched and contains records.
return (
<ul>
{users.map(user => (
<li key={user.id}>
{user.name}
</li>
))}
</ul>
);
The application displays the actual data when the request succeeds.
3. Understanding the State Flow
4. Recommended Approach: Use a Single Status State
For simple API requests, you can manage the request using separate loading, error, and data states.
However, as an application grows, a single status state can make the possible UI states easier to understand and control.
const [status, setStatus] = useState("loading");
const [users, setUsers] = useState([]);
const [error, setError] = useState("");
Possible status values:
"loading"
"error"
"empty"
"success"
The advantage is that the UI has one clearly defined request status instead of several independent Boolean flags.
5. Complete Practical Example Using React Hooks
Let's create a Users component that handles all four states.
import { useEffect, useState } from "react";
function Users() {
const [users, setUsers] = useState([]);
const [status, setStatus] = useState("loading");
const [error, setError] = useState("");
async function fetchUsers(signal) {
setStatus("loading");
setError("");
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users",
{ signal }
);
if (!response.ok) {
throw new Error(
`Request failed: ${response.status}`
);
}
const data = await response.json();
setUsers(data);
if (data.length === 0) {
setStatus("empty");
} else {
setStatus("success");
}
}
catch (err) {
if (err.name === "AbortError") {
return;
}
setError(err.message);
setStatus("error");
}
}
useEffect(() => {
const controller = new AbortController();
fetchUsers(controller.signal);
return () => {
controller.abort();
};
}, []);
if (status === "loading") {
return <p>Loading users...</p>;
}
if (status === "error") {
return (
<div>
<p>Error: {error}</p>
<button onClick={() => {
const controller = new AbortController();
fetchUsers(controller.signal);
}}>
Retry
</button>
</div>
);
}
if (status === "empty") {
return <p>No users available.</p>;
}
return (
<div>
<h2>Users</h2>
<ul>
{users.map(user => (
<li key={user.id}>
{user.name} - {user.email}
</li>
))}
</ul>
</div>
);
}
export default Users;
How it works:
- Initially, the status is
loading. - The component sends an API request.
- If the request fails, the status becomes
error. - If the response contains an empty array, the status becomes
empty. - If the response contains records, the status becomes
success. - The component displays the UI corresponding to the current status.
- The Retry button allows the user to try the request again.
Note: This example demonstrates the four states for an initial data request. In a production application, it is often better to define the retry function with a stable lifecycle and manage cancellation for every request. A retry should not update component state after the component has unmounted.
6. Alternative Approach: Separate State Variables
You can also use separate state variables.
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [users, setUsers] = useState([]);
The UI can be rendered as follows:
if (loading) {
return <p>Loading...</p>;
}
if (error) {
return <p>Error: {error}</p>;
}
if (users.length === 0) {
return <p>No users found.</p>;
}
return (
<ul>
{users.map(user => (
<li key={user.id}>
{user.name}
</li>
))}
</ul>
);
This approach is easy to understand for small components.
However, independent state variables can accidentally represent contradictory situations. For example, loading and error could both be true. Make sure your state transitions prevent such combinations.
7. Loading UI: Spinner vs Skeleton
There are different ways to represent loading.
Spinner
A spinner indicates that an operation is in progress.
function Loading() {
return <p>Loading data...</p>;
}
Use it for:
- Small API requests.
- Button submissions.
- Short operations.
Skeleton Screen
A skeleton screen displays placeholders that resemble the final content.
function UserSkeleton() {
return (
<div>
<p>Loading name...</p>
<p>Loading email...</p>
<p>Loading phone...</p>
</div>
);
}
Use it for:
- Dashboard cards.
- Product lists.
- Profile pages.
- Large content sections.
A skeleton can help users understand the expected page layout while data is loading.
8. Handling Form Submission States
The same concept applies to forms.
import { useState } from "react";
function LoginForm() {
const [status, setStatus] = useState("idle");
const [error, setError] = useState("");
async function handleSubmit(event) {
event.preventDefault();
setStatus("loading");
setError("");
try {
const response = await fetch("/api/login", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
username: "demo",
password: "example"
})
});
if (!response.ok) {
throw new Error("Login failed");
}
setStatus("success");
}
catch (err) {
setError(err.message);
setStatus("error");
}
}
return (
<form onSubmit={handleSubmit}>
<button
type="submit"
disabled={status === "loading"}
>
{status === "loading"
? "Submitting..."
: "Login"}
</button>
{status === "error" && (
<p>{error}</p>
)}
{status === "success" && (
<p>Login successful!</p>
)}
</form>
);
}
This is an illustrative example. A real login form should collect credentials from user inputs and follow the application's authentication and security requirements.
9. Handling States with TanStack Query
In real-world React applications, manually managing loading, error, and data states for every API request can become repetitive.
Libraries such as TanStack Query provide built-in request-state management.
import { useQuery } from "@tanstack/react-query";
async function fetchUsers() {
const response = await fetch("/api/users");
if (!response.ok) {
throw new Error("Failed to fetch users");
}
return response.json();
}
function Users() {
const {
data: users,
isPending,
isError,
error
} = useQuery({
queryKey: ["users"],
queryFn: fetchUsers
});
if (isPending) {
return <p>Loading users...</p>;
}
if (isError) {
return <p>Error: {error.message}</p>;
}
if (users.length === 0) {
return <p>No users found.</p>;
}
return (
<ul>
{users.map(user => (
<li key={user.id}>
{user.name}
</li>
))}
</ul>
);
}
TanStack Query manages many server-state concerns, including:
- Loading and error states.
- Caching API responses.
- Refetching data.
- Background updates.
- Request deduplication.
- Retry configuration.
Important: isPending indicates that the query has no data yet and is pending. For an already loaded query that is being refreshed, isFetching can be used to indicate background fetching without replacing the existing content with a full-page loading screen.
For example:
const {
data: users,
isPending,
isFetching
} = useQuery({
queryKey: ["users"],
queryFn: fetchUsers
});
if (isPending) {
return <p>Loading users...</p>;
}
return (
<div>
{isFetching && <p>Refreshing...</p>}
{users.length === 0
? <p>No users found.</p>
: users.map(user => (
<p key={user.id}>{user.name}</p>
))
}
</div>
);
10. Important Difference: Initial Loading vs Background Fetching
These two situations should not always display the same UI.
Initial loading:
- No data is available yet.
- Display a spinner or skeleton.
- The main content is not ready.
Background fetching:
- Previously fetched data is already available.
- A new request is running.
- Keep the existing content visible.
- Optionally display a small refreshing indicator.
This avoids unnecessarily replacing the entire page whenever data is refreshed.
11. Common Mistakes to Avoid
- Showing an empty message during loading: Check the loading state before checking whether the array is empty.
- Treating an empty response as an error: An empty array can be a successful API response.
- Not checking response.ok: Fetch does not automatically reject HTTP error responses such as 404 or 500.
- Not providing retry functionality: Users should have a way to recover from temporary failures where appropriate.
- Displaying technical error messages directly: Show understandable messages to users and log technical details appropriately.
- Replacing existing data during background refresh: Keep existing data visible when possible.
- Ignoring request cancellation: Prevent unnecessary requests and updates after a component is no longer active.
- Allowing repeated form submissions: Disable the submit button while a submission is in progress.
- Using too many independent Boolean states: Prevent contradictory combinations of loading, error, and success.
12. Best Practices
- Always plan for loading, error, empty, and success states.
- Keep the UI simple and consistent.
- Use skeletons for content-heavy screens where appropriate.
- Provide useful error messages.
- Add retry functionality when it makes sense.
- Distinguish initial loading from background fetching.
- Avoid showing an empty state before the API request completes.
- Use a reusable component for common loading and error UI.
- Consider TanStack Query for applications with many API requests.
- Handle cancellation and stale responses when requests can overlap.
- Do not expose sensitive server details or stack traces to users.
13. Quick Comparison
| State | Meaning | UI Example |
|---|---|---|
| Loading | Request is in progress | Spinner or skeleton |
| Error | Request failed | Error message and retry |
| Empty | Request succeeded, no records | No data available |
| Success | Request succeeded with records | Display data |
14. Interview Questions and Answers
Q1. What are loading, error, empty, and success states in React?
They represent the different outcomes of an asynchronous operation. Loading indicates an ongoing request, error indicates failure, empty indicates successful retrieval without records, and success indicates that usable data is available.
Q2. Is an empty state the same as an error state?
No. An empty state means the request succeeded but returned no records. An error state means the request failed.
Q3. How do you manage API loading and error states in React?
We can use useState to manage request status and data, or use a library such as TanStack Query to manage server-state requests.
Q4. What is the difference between isPending and isFetching in TanStack Query?
isPending indicates that a query is pending without available data. isFetching indicates that a fetch operation is currently running, including background refetches.
Q5. Why should we check response.ok when using Fetch?
Fetch generally resolves its Promise even when the server responds with HTTP errors such as 404 or 500. Checking response.ok allows us to handle these responses explicitly.
Q6. Why should we not display a loading screen during every background refresh?
Because existing data is already available. Keeping it visible provides a smoother experience and avoids unnecessary page flickering.
Q7. How can we implement retry functionality?
We can provide a Retry button that triggers the API request again. TanStack Query also supports configurable retry behavior.
Q8. Which approach is better: separate Boolean states or a single status state?
Both approaches work. Separate states are simple for small components, while a single status state makes mutually exclusive request states easier to manage.
15. Final Takeaway
Handling loading, error, empty, and success states is an essential part of building reliable React applications.
A good React component should not only display data when an API request succeeds. It should also provide a clear and useful experience while waiting for data, when something goes wrong, and when no records are available.
For small applications, useState and useEffect may be sufficient. For larger applications, TanStack Query can simplify server-state management, caching, refetching, and request handling.
| How to Organize API Calls in a React Application :👈 | 👉:How to Design Reusable React Components |
Comments and Discussion