0
0
Reactframework~30 mins

Using error boundaries in React - Mini Project: Build & Apply

Choose your learning style9 modes available
Using error boundaries
📖 Scenario: You are building a React app that shows user profiles. Sometimes, the profile data might cause errors when rendering. To keep the app running smoothly, you want to catch these errors and show a friendly message instead of a broken screen.
🎯 Goal: Create a React error boundary component that catches errors in its child components and displays a fallback UI. Then use this error boundary to wrap a component that might throw an error.
📋 What You'll Learn
Create a class component called ErrorBoundary that implements componentDidCatch and getDerivedStateFromError methods.
Add a state property hasError to track if an error happened.
Render a fallback UI with the text Something went wrong. when an error is caught.
Wrap a child component called UserProfile inside ErrorBoundary in the main app component.
💡 Why This Matters
🌍 Real World
Error boundaries help keep React apps running smoothly by catching unexpected errors in parts of the UI and showing friendly messages instead of crashing the whole app.
💼 Career
Understanding error boundaries is important for React developers to build resilient user interfaces and improve user experience by handling errors gracefully.
Progress0 / 4 steps
1
Create the UserProfile component
Create a functional React component called UserProfile that returns a <div> with the text User Profile Loaded.
React
Need a hint?

Use a simple function that returns JSX with the exact text inside a div.

2
Create the ErrorBoundary class component
Create a class component called ErrorBoundary that extends React.Component. Add a state property hasError initialized to false.
React
Need a hint?

Use a constructor to set initial state with hasError: false.

3
Add error handling methods to ErrorBoundary
Inside ErrorBoundary, add a static method getDerivedStateFromError that sets hasError to true. Also add componentDidCatch that receives error and info parameters but does nothing inside.
React
Need a hint?

Use getDerivedStateFromError to update state and show fallback UI in render.

4
Use ErrorBoundary to wrap UserProfile in the main app
Create a functional component called App that returns ErrorBoundary wrapping UserProfile. Export App as default.
React
Need a hint?

Wrap UserProfile inside ErrorBoundary tags in the App component.