Loading and Error States in React
Loading and error states are important concepts in React that help developers manage asynchronous operations, especially when fetching data from APIs. A loading state informs users that data is being processed, while an error state communicates when something goes wrong. These states improve the user experience by making applications more responsive, understandable, and reliable.
Course Links: JustAcademy React JS Training | Register for React JS Course Demo
1. What Are Loading and Error States?
Loading State
A loading state represents a period when an application is waiting for an operation to complete. For example, when a React component requests a list of products from an API, the application may display a loading message or spinner until the data arrives.
Error State
An error state represents a situation in which an operation cannot be completed successfully. An API might be unavailable, the network might disconnect, or the server might return an unsuccessful HTTP status.
Example
Loading... Please wait.
Success: Products loaded successfully.
Error: Unable to load products. Please try again.
These messages help users understand what the application is doing instead of leaving them looking at an empty screen.
2. Why Are Loading and Error States Important?
- Better user experience: Users receive feedback while an operation is in progress.
- Clear communication: Error messages explain when data cannot be retrieved.
- Reduced confusion: Users can distinguish an empty result from a request that is still loading.
- Improved reliability: Applications can handle network and server problems gracefully.
- Better interaction: Buttons can be disabled while a request is being submitted to help prevent duplicate actions.
- Easier debugging: Developers can identify whether a problem occurred during a request.
3. Understanding the Different UI States
A data-fetching component commonly manages four main states: loading, success, empty, and error.
| State |
Description |
Example Message |
| Loading |
The request is still in progress. |
Loading products... |
| Success |
The request succeeded and data is available. |
Products loaded successfully. |
| Empty |
The request succeeded but returned no records. |
No products found. |
| Error |
The request failed or returned an unsuccessful HTTP status. |
Unable to load products. |
Important: An empty state is not necessarily an error. An API can successfully return an empty array when no records match the request.
4. Managing Loading and Error States with useState
The React useState Hook allows a component to store information that affects its displayed output. You can use separate state variables to track loading, error messages, and retrieved data.
Basic Syntax
import { useState } from "react";
function ExampleComponent() {
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [data, setData] = useState([]);
return (
<div>
{loading && <p>Loading...</p>}
{error && <p>{error}</p>}
{!loading && !error && (
<p>Ready to display data.</p>
)}
</div>
);
}
export default ExampleComponent;
Explanation
loading indicates whether an operation is in progress.
error stores a message when an operation fails.
data stores the retrieved information.
setLoading(), setError(), and setData() update the corresponding state variables.
- When state changes, React re-renders the component so the interface reflects the latest state.
5. Fetching API Data with Loading and Error States
When retrieving data from an API, a component typically begins in a loading state, requests the data, and then displays either the result or an error message.
Example: Fetching Products
import { useEffect, useState } from "react";
function Products() {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
const controller = new AbortController();
async function fetchProducts() {
try {
setLoading(true);
setError("");
const response = await fetch(
"https://dummyjson.com/products",
{ signal: controller.signal }
);
if (!response.ok) {
throw new Error("Failed to load products.");
}
const result = await response.json();
if (!controller.signal.aborted) {
setProducts(result.products ?? []);
}
} catch (err) {
if (err.name !== "AbortError") {
setError(
err.message || "Something went wrong."
);
}
} finally {
if (!controller.signal.aborted) {
setLoading(false);
}
}
}
fetchProducts();
return () => {
controller.abort();
};
}, []);
if (loading) {
return <p>Loading products...</p>;
}
if (error) {
return (
<div>
<p role="alert">Error: {error}</p>
</div>
);
}
if (products.length === 0) {
return <p>No products found.</p>;
}
return (
<div>
<h2>Product List</h2>
<ul>
{products.map(product => (
<li key={product.id}>
{product.title} - ${product.price}
</li>
))}
</ul>
</div>
);
}
export default Products;
How This Example Works
useState initializes the product list, loading status, and error message.
useEffect starts the API request when the component mounts.
fetch() sends a GET request to the API.
response.ok checks whether the HTTP status indicates success.
response.json() parses the response body.
setProducts() saves the retrieved product data.
- If an error occurs,
setError() stores an appropriate message.
- The
finally block clears the loading state unless the request was cancelled.
- The component renders the appropriate loading, error, empty, or success UI.
AbortController cancels the request during cleanup if it is still in progress.
Note: DummyJSON is a public sample API used for learning and testing. Use your own API endpoint for production applications.
6. Understanding Conditional Rendering
Conditional rendering means displaying different UI elements depending on the current state of the component. It is one of the most common ways to handle loading and error states in React.
Using If Statements
if (loading) {
return <p>Loading data...</p>;
}
if (error) {
return <p role="alert">{error}</p>;
}
return <p>Data loaded successfully.</p>;
Using the Logical AND Operator
{loading && <p>Loading data...</p>}
{error && <p role="alert">{error}</p>}
The logical AND operator displays the element when its condition is true.
Using the Ternary Operator
{loading
? <p>Loading data...</p>
: <p>Data is ready.</p>}
The ternary operator chooses one of two UI outputs based on a condition. For multiple states, separate if statements can be easier to read.
7. Creating a Loading Spinner
A loading spinner provides a visual indication that an operation is still running. A simple text message can work well too, particularly when a spinner would add unnecessary visual noise.
Example: CSS Spinner
function LoadingSpinner() {
return (
<div className="loading-container">
<div className="spinner" aria-hidden="true"></div>
<p role="status">Loading, please wait...</p>
</div>
);
}
export default LoadingSpinner;
CSS Styling
.loading-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
padding: 24px;
}
.spinner {
width: 36px;
height: 36px;
border: 4px solid #dddddd;
border-top-color: #2563eb;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
Using the Spinner
{loading ? (
<LoadingSpinner />
) : (
<ProductList products={products} />
)}
Keep a readable status message alongside the spinner so users who rely on assistive technology can understand what is happening.
8. Displaying Error Messages
Error messages should clearly explain the problem and, when possible, tell users what they can do next.
Example Error Messages
- Network error: Unable to connect. Check your internet connection.
- Server error: The service is temporarily unavailable. Please try again later.
- Not found: The requested information could not be found.
- Validation error: Please enter all required information.
- Authentication error: Please sign in again to continue.
Example Error Component
function ErrorMessage({ message, onRetry }) {
return (
<div className="error-container" role="alert">
<p>{message}</p>
{onRetry && (
<button onClick={onRetry}>
Try Again
</button>
)}
</div>
);
}
export default ErrorMessage;
CSS Styling
.error-container {
padding: 16px;
border: 1px solid #dc2626;
border-radius: 8px;
background: #fef2f2;
color: #991b1b;
}
.error-container button {
padding: 8px 14px;
cursor: pointer;
}
Avoid displaying raw stack traces, internal server details, credentials, or other sensitive information to end users.
9. Adding a Retry Button
A retry button allows users to repeat an operation after a temporary failure. For example, a user might retry a request after reconnecting to the internet.
Example: Retryable Data Fetching
import { useCallback, useEffect, useState } from "react";
function UserList() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const [attempt, setAttempt] = useState(0);
const loadUsers = useCallback(async (signal) => {
setLoading(true);
setError("");
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users",
{ signal }
);
if (!response.ok) {
throw new Error("Unable to load users.");
}
const data = await response.json();
if (!signal.aborted) {
setUsers(data);
}
} catch (err) {
if (err.name !== "AbortError") {
setError(err.message || "Request failed.");
}
} finally {
if (!signal.aborted) {
setLoading(false);
}
}
}, []);
useEffect(() => {
const controller = new AbortController();
loadUsers(controller.signal);
return () => controller.abort();
}, [loadUsers, attempt]);
if (loading) {
return <p role="status">Loading users...</p>;
}
if (error) {
return (
<div>
<p role="alert">{error}</p>
<button onClick={() => setAttempt(value => value + 1)}>
Retry
</button>
</div>
);
}
return (
<div>
<h2>Users</h2>
{users.length === 0 ? (
<p>No users found.</p>
) : (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
)}
</div>
);
}
export default UserList;
How Retry Works
- The initial request loads the user list.
- If the request fails, the error message and Retry button appear.
- Clicking Retry increments the
attempt state.
- The effect runs again and sends a new request.
- The component displays the resulting data or another error message.
10. Handling Loading and Error States in Form Submission
Loading and error states are also important when submitting forms. A form should indicate when data is being saved, prevent accidental repeated submissions where appropriate, and display a useful result.
Example: Submit a Contact Form
import { useState } from "react";
function ContactForm() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [status, setStatus] = useState("idle");
const [error, setError] = useState("");
async function handleSubmit(event) {
event.preventDefault();
setStatus("loading");
setError("");
try {
const response = await fetch(
"https://api.example.com/contact",
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ name, email })
}
);
if (!response.ok) {
throw new Error("Unable to submit the form.");
}
setStatus("success");
setName("");
setEmail("");
} catch (err) {
setStatus("error");
setError(err.message || "Something went wrong.");
}
}
return (
<form onSubmit={handleSubmit}>
<h2>Contact Us</h2>
<input
value={name}
onChange={event => setName(event.target.value)}
placeholder="Your name"
required
/>
<input
type="email"
value={email}
onChange={event => setEmail(event.target.value)}
placeholder="Your email"
required
/>
<button type="submit" disabled={status === "loading"}>
{status === "loading" ? "Submitting..." : "Submit"}
</button>
{status === "success" && (
<p role="status">Form submitted successfully!</p>
)}
{status === "error" && (
<p role="alert">{error}</p>
)}
</form>
);
}
export default ContactForm;
Note: Replace the placeholder URL with your real backend endpoint. This example uses a status variable to represent idle, loading, success, and error states. The backend should validate the submitted information independently of client-side validation.
11. Boolean State vs. a Status Variable
There are different ways to represent loading and error states. Choosing a clear state structure helps prevent contradictory UI conditions.
| Approach |
Example |
Best Use |
| Separate variables |
loading, error, data |
Simple components and independent values. |
| Status variable |
idle, loading, success, error |
Operations with clearly defined stages. |
| Reducer |
useReducer with action types |
More complex state transitions or multiple related updates. |
Example Using a Status Variable
const [status, setStatus] = useState("idle");
// Before a request
setStatus("loading");
// After a successful request
setStatus("success");
// If the request fails
setStatus("error");
When using a status variable, render the UI based on its current value. For larger components, a reducer can help keep transitions predictable.
12. Common Mistakes to Avoid
- Forgetting to reset loading: Make sure the loading state is cleared after both successful and failed requests.
- Not checking HTTP status: With Fetch, a 404 or 500 response does not automatically reject the promise.
- Ignoring empty results: A successful request can return an empty collection.
- Showing confusing error messages: Use clear, user-friendly wording.
- Updating state after cancellation: Cancel requests or ignore results when an effect is cleaned up.
- Missing effect dependencies: Include reactive values used by the effect in its dependency list.
- Creating infinite request loops: Avoid changing effect dependencies unnecessarily.
- Leaving buttons enabled during submission: Disable controls when repeated actions could cause problems.
- Parsing an empty response as JSON: Check whether the response actually contains a body before parsing it.
- Displaying sensitive technical details: Keep internal server errors and private information out of user-facing messages.
13. Best Practices for Loading and Error States
- Initialize loading state according to whether data must be fetched immediately.
- Display loading feedback for operations that take noticeable time.
- Show success, empty, and error states separately.
- Use accessible status messages such as
role="status" and error alerts such as role="alert" where appropriate.
- Provide a retry option when repeating the operation is safe and useful.
- Use
try/catch/finally for asynchronous operations that need consistent cleanup.
- Cancel requests or ignore outdated responses when components unmount or inputs change.
- Keep error messages specific enough to guide the user without revealing sensitive details.
- Consider framework-supported data-fetching solutions or libraries when caching, retries, and request coordination become complex.
- Test network failures, HTTP errors, slow requests, and empty responses.
14. Practical Project: Product Dashboard
Objective: Build a React product dashboard that retrieves product information from an API and handles loading and error conditions.
Project Requirements
- Fetch products from an API.
- Display a loading message while the request is running.
- Show a list of products after a successful response.
- Display an empty-state message when no products are returned.
- Show a helpful error message if the request fails.
- Add a Retry button to repeat a failed request.
- Disable relevant controls while an operation is in progress.
- Make status and error messages accessible.
Expected UI Flow
Page Opens
|
v
Loading Products...
|
+---- Request Successful ----> Display Products
| |
| +-- No records? Show Empty State
|
+---- Request Failed --------> Display Error + Retry Button
Suggested Enhancements
- Add a search field to filter products.
- Display product images and prices.
- Add pagination for large product lists.
- Use a reusable Loading component.
- Create a reusable ErrorMessage component.
- Test the application with simulated network failures.
15. Interview Questions and Answers
Q1. What is a loading state in React?
A loading state indicates that an asynchronous operation, such as an API request, is still in progress.
Q2. What is an error state?
An error state represents a failed operation and allows the application to display an appropriate error message or recovery option.
Q3. Which Hook is commonly used to manage loading and error states?
useState is commonly used to store loading flags, error messages, and fetched data.
Q4. Why is useEffect used when fetching data?
useEffect can synchronize a component with an external system, such as an API, when the component mounts or its dependencies change.
Q5. Why should loading state be reset in a finally block?
A finally block runs after the try/catch flow, making it useful for clearing loading state after success or failure. Cancellation logic may need special handling.
Q6. What is conditional rendering?
Conditional rendering means displaying different elements based on conditions or state values.
Q7. How can users retry a failed request?
A Retry button can trigger the request again, either by calling a request function or updating a dependency that causes an effect to run again.
Q8. What is the difference between an empty state and an error state?
An empty state means the request succeeded but produced no records. An error state means the request failed or could not be processed successfully.
Q9. What is AbortController used for?
AbortController can cancel supported requests, helping prevent unnecessary work when the result is no longer needed.
Q10. How do you improve accessibility for loading and error messages?
Use clear text, appropriate status or alert semantics, keyboard-accessible controls, and meaningful button labels.
16. Practice Exercises
- Create a component that displays a loading message while fetching users.
- Add an error state for failed API requests.
- Display a separate empty-state message when the API returns an empty array.
- Create a reusable loading spinner using CSS.
- Add a Retry button to an API-driven component.
- Disable a form's submit button while the request is running.
- Display a success message after a form submission completes.
- Cancel an API request when the component unmounts.
- Test the component with slow responses, server errors, and network failures.
17. Conclusion
Loading and error states are essential for creating user-friendly React applications. By combining useState, useEffect, asynchronous JavaScript, conditional rendering, request cancellation, and appropriate error handling, developers can build interfaces that communicate clearly during every stage of an API operation.
Explore more learning resources through JustAcademy React JS Training or Register for React JS Course Demo.
Official References