Displaying Loading and Error States
×


Displaying Loading and Error States

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!



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