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.
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.
Letβs use the useState
and useEffect
hooks to manage three states:
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>; }
Use distinct colors and font styles for each state. For example:
If you're dealing with multiple requests or want better caching, you can use libraries like:
React Query
(TanStack Query)SWR
(by Vercel)Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!