Displaying Loading and Error States
0 526
๐ฏ Why Handle Loading and Error States?
In a React app, displaying loading and error states enhances user experience by providing immediate feedback. Whether you're fetching data from an API or submitting a form, users should know whatโs happening. โณโ ๏ธ
๐ Basic Pattern with useEffect
Let's break down a typical use case: fetching data with loading and error feedback.
import { useEffect, useState } from "react";
function UsersList() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch("https://api.example.com/users")
.then((res) => {
if (!res.ok) throw new Error("Failed to fetch users.");
return res.json();
})
.then((data) => {
setUsers(data);
setLoading(false);
})
.catch((err) => {
setError(err.message);
setLoading(false);
});
}, []);
if (loading) return <p>๐ Loading users...</p>;
if (error) return <p className="text-red-500">โ {error}</p>;
return (
<ul>
{users.map(user => (
<li key={user.id}>๐ค {user.name}</li>
))}
</ul>
);
}
โณ Better Loading UX Options
Instead of plain text, you can use:
- ๐๏ธ Spinners (via libraries like
react-spinners) - ๐ Skeleton loaders (e.g.,
react-loading-skeleton) - ๐ Disabled buttons with "Loading..." text
๐ Conditional Rendering Strategy
Use clean and consistent patterns:
if (loading) return <LoadingSpinner />;
if (error) return <ErrorMessage message={error} />;
return <DataList items={data} />;
๐ฅ Error State UX Tips
- ๐ Be specific: Show a clear message, e.g., "Could not load products."
- ๐ Add a "Retry" button
- ๐งฉ Optionally show fallback content
๐งช Example: Retry Button
<div>
<p>โ {error}</p>
<button onClick={fetchData} className="bg-blue-500 text-white p-2">
Retry
</button>
</div>
๐ง Custom Hook for Loading and Error
Extract logic into reusable hooks:
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch(url)
.then(res => res.ok ? res.json() : Promise.reject("Error loading data"))
.then(data => {
setData(data);
setLoading(false);
})
.catch(err => {
setError(err);
setLoading(false);
});
}, [url]);
return { data, loading, error };
}
๐ Summary
- โ Always handle loading and error states
- โ Use conditional rendering for clean UX
- โ Provide visual feedback and fallback options
- โ Extract into hooks for DRY code
๐ Final Thoughts
Displaying loading and error states may seem small, but itโs a huge part of a polished, user-friendly React application. Never leave your users guessing! Show them whatโs happening behind the scenes. โ๏ธ๐
If youโre passionate about building a successful blogging website, check out this helpful guide at Coding Tag โ How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:




Comments
Waiting for your comments