javascript / intermediate
Snippet
Declarative UI Recovery via Class Error Boundaries
React error boundaries rely on JavaScript class inheritance and lifecycle methods to catch unhandled errors in child component trees during rendering, lifecycles, and constructors. By defining `static getDerivedStateFromError`, the component synchronously modifies state to render a graceful fallback UI instead of unmounting the entire application.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import React, { Component } from 'react';class SafeBoundary extends Component {state = { hasError: false, error: null };static getDerivedStateFromError(error) {return { hasError: true, error };}componentDidCatch(error, errorInfo) {console.error('Uncaught runtime error:', error, errorInfo.componentStack);}resetError = () => {this.setState({ hasError: false, error: null });};render() {if (this.state.hasError) {return (<div role="alert"><p>Something went wrong: {this.state.error?.message}</p><button onClick={this.resetError}>Retry Action</button></div>);}return this.props.children;}}export default SafeBoundary;
react
Breakdown
1
class SafeBoundary extends Component {
Extends React.Component to establish a class-based boundary with lifecycle access.
2
static getDerivedStateFromError(error) {
Static lifecycle method that catches thrown errors and returns updated state to trigger the fallback UI.
3
componentDidCatch(error, errorInfo) {
Lifecycle hook that receives the error and component stack trace for telemetry and logging purposes.