REACT Tutorial



LOADING & ERROR HANDLING


Loading and Error Handling in React

When working with asynchronous operations like API requests in React, it's essential to inform users about what's happening β€” whether data is still loading, or if something went wrong. Let’s learn how to handle these states gracefully.

Why This Matters

Without loading and error states, your app may look broken or unresponsive when users wait for data or encounter a network issue. A polished UI always reflects the application's state clearly.

Step-by-Step: Add Loading and Error States

Let’s use the useState and useEffect hooks to manage three states:

  • Loading: true while data is being fetched.
  • Error: stores any error message if something fails.
  • Data: stores the actual response if fetch is successful.
import React, { useState, useEffect } from 'react';

function JokeFetcher() {
  const [joke, setJoke] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('https://official-joke-api.appspot.com/jokes/random')
      .then(res => {
        if (!res.ok) throw new Error('Failed to fetch a joke');
        return res.json();
      })
      .then(data => {
        setJoke(data.setup + ' - ' + data.punchline);
        setLoading(false);
      })
      .catch(err => {
        setError(err.message);
        setLoading(false);
      });
  }, []);

  if (loading) return <p style={{color:'#e67e22'}}>Loading joke...</p>;
  if (error) return <p style={{color:'red'}}>Error: {error}</p>;

  return <p style={{fontSize:'18px', fontWeight:'600'}}>{joke}</p>;
}

πŸ’‘ Output Based on State

  • While fetching: Shows β€œLoading joke...”
  • If error: Displays red error message
  • If successful: Displays the joke

Styling Tip 🎨

Use distinct colors and font styles for each state. For example:

  • Orange for loading
  • Red for errors
  • Green or black for successful data

Advanced Tip πŸš€

If you're dealing with multiple requests or want better caching, you can use libraries like:

  • React Query (TanStack Query)
  • SWR (by Vercel)
These handle loading/error states automatically and reduce boilerplate code.

Good loading and error handling shows users that your app is reliable β€” even when the internet isn’t!
Try Live Example ➀

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review