patternjavascriptreactMajorpending
Pattern: Error boundary with fallback UI in React
Viewed 0 times
error-boundaryfallbackcrashgetDerivedStateFromErrorcomponentDidCatch
Problem
An uncaught error in a React component crashes the entire app. Need graceful degradation at component level.
Solution
Use Error Boundaries to catch and display fallback UI:
class ErrorBoundary extends React.Component {
state = { hasError: false, error: null };
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, info) {
console.error('Error boundary caught:', error, info.componentStack);
// Send to error tracking service
}
render() {
if (this.state.hasError) {
return this.props.fallback || (
<div role='alert'>
<h2>Something went wrong</h2>
<button onClick={() => this.setState({ hasError: false })}>
Try again
</button>
</div>
);
}
return this.props.children;
}
}
// Usage - wrap risky components:
<ErrorBoundary fallback={<p>Widget failed to load</p>}>
<ComplexWidget />
</ErrorBoundary>
// Granular boundaries:
<ErrorBoundary><Header /></ErrorBoundary>
<ErrorBoundary><MainContent /></ErrorBoundary>
<ErrorBoundary><Sidebar /></ErrorBoundary>
class ErrorBoundary extends React.Component {
state = { hasError: false, error: null };
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, info) {
console.error('Error boundary caught:', error, info.componentStack);
// Send to error tracking service
}
render() {
if (this.state.hasError) {
return this.props.fallback || (
<div role='alert'>
<h2>Something went wrong</h2>
<button onClick={() => this.setState({ hasError: false })}>
Try again
</button>
</div>
);
}
return this.props.children;
}
}
// Usage - wrap risky components:
<ErrorBoundary fallback={<p>Widget failed to load</p>}>
<ComplexWidget />
</ErrorBoundary>
// Granular boundaries:
<ErrorBoundary><Header /></ErrorBoundary>
<ErrorBoundary><MainContent /></ErrorBoundary>
<ErrorBoundary><Sidebar /></ErrorBoundary>
Why
Error boundaries contain failures to specific subtrees, preventing one broken component from crashing the whole app.
Revisions (0)
No revisions yet.