In JavaScript, an unhandled exception thrown inside a component's render method used to corrupt React's internal state and cause the entire web page to unmount, leaving the user with an empty white screen. Error Boundaries provide a protective safety net: if a single card or widget crashes, only that card displays a friendly fallback message while the rest of the application remains fully interactive.
// src/components/ErrorBoundary.jsx
import React, { Component } from 'react';
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false, errorMessage: '' };
}
// 1. Update state so next render shows fallback UI
static getDerivedStateFromError(error) {
return { hasError: true, errorMessage: error.message };
}
// 2. Log error details to an external monitoring service (e.g. Sentry)
componentDidCatch(error, errorInfo) {
console.error('ErrorBoundary caught an unhandled error:', error, errorInfo);
}
handleRetry = () => {
this.setState({ hasError: false, errorMessage: '' });
};
render() {
if (this.state.hasError) {
return (
<div className="error-fallback-card" style={{ padding: '20px', border: '1px solid #ef4444', borderRadius: '8px', background: '#fef2f2' }}>
<h3 style={{ color: '#b91c1c', marginTop: 0 }}>Something went wrong in this widget.</h3>
<p style={{ color: '#7f1d1d' }}>{this.state.errorMessage}</p>
<button onClick={this.handleRetry} style={{ background: '#5dbe59', color: '#fff', border: 'none', padding: '8px 16px', borderRadius: '4px', cursor: 'pointer' }}>
Retry Component
</button>
</div>
);
}
return this.props.children;
}
}
export default ErrorBoundary;
function Dashboard() {
return (
<div className="dashboard-grid">
<Navbar />
{/* Protected Widget */}
<ErrorBoundary>
<LiveStockFeed />
</ErrorBoundary>
<Footer />
</div>
);
}
Now let us examine clean DOM tree preservation in React Fragments & StrictMode.
Accelerate your React mastery by studying these tightly connected core tutorials:
Graceful fallback UI for async component loading.
getDerivedStateFromError and componentDidCatch.
Simulating component crashes using React Testing Library.