Displaying Loading and Error States
×


Displaying Loading and Error States

722

🎯 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!



Best WordPress Hosting


Share:


Discount Coupons

Unlimited Video Generation

Best Platform to generate videos

Search and buy from Namecheap

Secure Domain for a Minimum Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat