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