Loading and Error States
When making HTTP requests in React, the data isn't available immediately. Users need to know what's happening whether the app is loading, if an error occurred, or if the data has arrived. Handling **loading and error states** is crucial for a good user experience.
The Three States of Data Fetching
Every data fetching operation has three possible states:
- Loading: The request is in progress, and we're waiting for a response.
- Success: The request succeeded, and we have data to display.
- Error: The request failed, and we need to show an error message.
Always handle all three states. Never leave your users wondering if something is broken or just slow.
Basic Pattern with useState
import React, { useState, useEffect } from 'react';import axios from 'axios';
function DataFetcher() { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null);
useEffect(() => { <!-- Start loading --> setLoading(true); setError(null);
axios.get('https://api.example.com/data') .then(response => { setData(response.data); setLoading(false); }) .catch(err => { setError(err.message); setLoading(false); }); }, []);
<!-- Render based on state --> if (loading) { return <div className="loader">Loading... Please wait.</div>; }
if (error) { return ( <div className="error"> <h3>Something went wrong!</h3> <p>{error}</p> </div> ); }
<!-- Success state --> return ( <div> <h1>Data Loaded Successfully</h1> <pre>{JSON.stringify(data, null, 2)}</pre> </div> );}Loading UI Patterns
- Spinners: Simple loading indicators.
- Skeleton screens: Placeholder shapes that mimic the final layout (better UX).
- Progress bars: For longer operations.
Error UI Patterns
- Display a friendly error message.
- Provide a "Retry" button.
- Log errors for debugging.
Two Minute Drill
- Always track three states: loading, success, and error.
- Use separate state variables: `data`, `loading`, `error`.
- Show loading indicators while waiting for data.
- Display clear error messages when requests fail.
- Consider adding retry functionality for better UX.
Need more clarification?
Drop us an email at career@quipoinfotech.com
