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

codeTap to expand ⛶
1// 1. The Class-based Error Boundary
2import React from 'react';
3
4class ErrorBoundary extends React.Component {
5 constructor(props) {
6 super(props);
7 this.state = { hasError: false };
8 }
9
10 // Update state so the next render will show the fallback UI
11 static getDerivedStateFromError(error) {
12 return { hasError: true };
13 }
14
15 componentDidCatch(error, errorInfo) {
16 // You can log the error to a service like Sentry or LogRocket
17 console.error("Caught by boundary:", error, errorInfo);
18 }
19
20 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 <button
26 onClick={() => window.location.reload()}
27 className="mt-2 text-sm underline"
28 >
29 Try reloading the page
30 </button>
31 </div>
32 );
33 }
34
35 return this.props.children;
36 }
37}
38
39// 2. Usage: Wrap risky components
40function App() {
41 return (
42 <div className="p-10">
43 <ErrorBoundary>
44 <Sidebar />
45 </ErrorBoundary>
46
47 <main>
48 <ErrorBoundary>
49 <UserProfile />
50 </ErrorBoundary>
51 </main>
52 </div>
53 );
54}

🏋️ Practice Exercise

  1. Create a 'BuggyComponent' that throws an error when a button is clicked. Observe the white screen of death.
  2. Implement an Error Boundary and wrap the 'BuggyComponent'. See the fallback UI.
  3. Use the popular react-error-boundary library to see how it simplifies error handling for functional components.
  4. 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