0
0
Reactframework~30 mins

Fallback UI patterns in React - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the UserProfile component with loading simulation
Create a React functional component called UserProfile that returns <div>User data loaded.</div>. Also create a variable called isLoading and set it to true.
React
Need a hint?

Start by declaring isLoading as true. Then create a function UserProfile that returns a div with the text 'User data loaded.'

2
Add Suspense with loading fallback UI
Create a React component called App that uses React.Suspense to wrap UserProfile. Set the fallback prop of Suspense to <div>Loading user data...</div>.
React
Need a hint?

Wrap UserProfile inside React.Suspense and provide a fallback div with the loading message.

3
Create an ErrorBoundary component for error fallback UI
Create a class component called ErrorBoundary that extends React.Component. It should have state { hasError: false }. Implement static getDerivedStateFromError() to set hasError to true. In render(), if hasError is true, return <div>Failed to load user data.</div>, else return this.props.children.
React
Need a hint?

Create a class component with error state. Use getDerivedStateFromError to update state on error. Show error message if error happened, else show children.

4
Wrap UserProfile with ErrorBoundary and Suspense in App
Update the App component to wrap UserProfile inside ErrorBoundary and then inside React.Suspense with the same fallback UI.
React
Need a hint?

Wrap UserProfile inside ErrorBoundary, then wrap that inside React.Suspense with the loading fallback.