An Error Boundary is a special React component that catches JavaScript errors in its child component tree during rendering, lifecycle methods, and constructors, and displays a fallback UI instead of crashing the whole app.
👉 Error boundaries must be class components.
🧠 Why Are Error Boundaries Needed?
Without error boundaries:
- A single runtime error can break the entire React app
- Users see a blank page or white screen
- Poor user experience
Error boundaries: ✔ Prevent app crashes
✔ Isolate failures to specific UI parts
✔ Show friendly fallback UI
✔ Allow logging errors
❌ What Errors Do They Catch?
✔ Errors during:
- Rendering
- Lifecycle methods
- Constructors of child components
❌ They do NOT catch:
- Event handlers
- Async code (
setTimeout,fetch) - Errors inside the error boundary itself
- Server-side rendering errors
🔑 Required Lifecycle Methods
1️⃣ static getDerivedStateFromError(error)
Used to update state and show fallback UI.
2️⃣ componentDidCatch(error, info)
Used to log error details.
🧪 Basic Error Boundary Example
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
console.error("Error caught:", error, info);
}
render() {
if (this.state.hasError) {
return <h2>Something went wrong.</h2>;
}
return this.props.children;
}
}
🧪 Usage
<ErrorBoundary>
<BuggyComponent />
</ErrorBoundary>
Only BuggyComponent fails — rest of the app works fine ✔
🔥 Real-World Use Cases
✔ Wrapping pages
✔ Wrapping widgets
✔ Wrapping third-party components
✔ Preventing white-screen crashes
Example:
<ErrorBoundary>
<Dashboard />
</ErrorBoundary>
🎯 Short Interview Answer
An Error Boundary is a React class component that catches rendering and lifecycle errors in its child components and displays a fallback UI instead of crashing the app.
It improves stability, user experience, and error handling in production applications.
⭐ One-Line Summary
Error boundaries protect your app from crashing due to UI errors.