Building a Fallback UI with React Suspense and Error Boundary
📖 Scenario: You are building a user profile page in a React app. Sometimes the profile data takes time to load or might fail to load. To keep the app friendly, you want to show a loading message while waiting and an error message if loading fails.
🎯 Goal: Create a React component that uses Suspense to show a loading fallback UI and an ErrorBoundary component to catch errors and show an error fallback UI.
📋 What You'll Learn
Create a simple React component called
UserProfile that simulates loading user data.Create a variable called
isLoading to control loading state.Use
React.Suspense with a fallback UI showing <div>Loading user data...</div>.Create an
ErrorBoundary component that shows <div>Failed to load user data.</div> on error.Wrap
UserProfile inside ErrorBoundary and Suspense in the main app component.💡 Why This Matters
🌍 Real World
Fallback UI patterns improve user experience by showing helpful messages during loading or errors, common in real web apps fetching data.
💼 Career
Understanding Suspense and ErrorBoundary is essential for React developers to build resilient and user-friendly interfaces.
Progress0 / 4 steps