Error Boundaries
0/3 in this phase0/36 across the roadmap
📖 Concept
React components that crash shouldn't take down the entire application. Error Boundaries are special components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.
Important Notes:
- Error Boundaries are currently the only thing that must be written as a Class Component (or use a library like
react-error-boundary). - They catch errors during rendering, in lifecycle methods, and in constructors.
- They do not catch errors in event handlers, asynchronous code, or server-side rendering.
💻 Code Example
code
1// 1. The Class-based Error Boundary2import React from 'react';34class ErrorBoundary extends React.Component {5 constructor(props) {6 super(props);7 this.state = { hasError: false };8 }910 // Update state so the next render will show the fallback UI11 static getDerivedStateFromError(error) {12 return { hasError: true };13 }1415 componentDidCatch(error, errorInfo) {16 // You can log the error to a service like Sentry or LogRocket17 console.error("Caught by boundary:", error, errorInfo);18 }1920 render() {21 if (this.state.hasError) {22 return (23 <div className="p-4 bg-red-50 border border-red-200 rounded">24 <h2 className="text-red-800 font-bold">Something went wrong.</h2>25 <button26 onClick={() => window.location.reload()}27 className="mt-2 text-sm underline"28 >29 Try reloading the page30 </button>31 </div>32 );33 }3435 return this.props.children;36 }37}3839// 2. Usage: Wrap risky components40function App() {41 return (42 <div className="p-10">43 <ErrorBoundary>44 <Sidebar />45 </ErrorBoundary>4647 <main>48 <ErrorBoundary>49 <UserProfile />50 </ErrorBoundary>51 </main>52 </div>53 );54}
🏋️ Practice Exercise
- Create a 'BuggyComponent' that throws an error when a button is clicked. Observe the white screen of death.
- Implement an Error Boundary and wrap the 'BuggyComponent'. See the fallback UI.
- Use the popular
react-error-boundarylibrary to see how it simplifies error handling for functional components. - Design a 'Global' error boundary and a 'Local' one for small UI widgets.
⚠️ Common Mistakes
Wrapping the entire app in a single Error Boundary (users will see a blank page if one small thing fails).
Thinking Error Boundaries catch async errors (they don't; you must handle those with try/catch in your effects).
Not logging errors caught by the boundary to a monitoring service.
💼 Interview Questions
🎤 Mock Interview
Practice a live interview for Error Boundaries
Was this topic helpful?