Fallback UI patterns show a simple message or design when the main content is loading or has an error. This helps users understand what is happening instead of seeing a blank screen.
0
0
Fallback UI patterns in React
Introduction
When loading data from the internet and you want to show a loading spinner or message.
When a part of your app crashes and you want to show a friendly error message.
When waiting for a slow component to load and you want to keep the user informed.
When you want to improve user experience by avoiding empty or broken screens.
Syntax
React
function Component({ loading, error }) { if (loading) { return <FallbackUI />; } if (error) { return <ErrorUI />; } return <MainContent />; }
Use simple conditional checks to decide which UI to show.
Fallback UI can be a spinner, message, or any React element.
Examples
Shows a loading message while waiting.
React
function Loading() { return <p>Loading...</p>; } function MyComponent({ loading }) { if (loading) { return <Loading />; } return <p>Data loaded!</p>; }
Shows an error message if there is a problem.
React
function ErrorFallback() { return <p>Oops! Something went wrong.</p>; } function MyComponent({ error }) { if (error) { return <ErrorFallback />; } return <p>All good!</p>; }
Combines loading and error fallback UIs.
React
function MyComponent({ loading, error }) { if (loading) return <p>Loading...</p>; if (error) return <p>Error occurred.</p>; return <p>Content is ready.</p>; }
Sample Program
This React component shows a loading message first. After 1.5 seconds, it either shows data or an error message. It uses fallback UI patterns to keep the user informed.
React
import React, { useState, useEffect } from 'react'; function Loading() { return <p aria-live="polite">Loading data, please wait...</p>; } function ErrorFallback() { return <p role="alert">Error loading data. Try again later.</p>; } function DataDisplay({ data }) { return <div> <h2>Data Loaded</h2> <pre>{JSON.stringify(data, null, 2)}</pre> </div>; } export default function App() { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(false); useEffect(() => { setTimeout(() => { // Simulate fetch success or failure const success = true; if (success) { setData({ message: 'Hello from server!' }); setLoading(false); } else { setError(true); setLoading(false); } }, 1500); }, []); if (loading) return <Loading />; if (error) return <ErrorFallback />; return <DataDisplay data={data} />; }
OutputSuccess
Important Notes
Always provide accessible roles and aria-live for fallback messages to help screen reader users.
Keep fallback UI simple and clear to avoid confusing users.
Test fallback UI by simulating slow network or errors in your app.
Summary
Fallback UI patterns improve user experience during loading or errors.
Use simple conditional rendering to show fallback content.
Make fallback UI accessible and easy to understand.