javascript / intermediate
Snippet
Catching React Render Errors with OOP Class Error Boundaries
React requires Object-Oriented class components to define Error Boundaries because functional hooks do not support getDerivedStateFromError or componentDidCatch lifecycles. By subclassing React.Component, static getDerivedStateFromError updates state synchronously to display fallback UI, while componentDidCatch provides an OOP method to log crash telemetry.
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
import React, { Component } from 'react';export class SafeErrorBoundary extends Component {constructor(props) {super(props);this.state = { hasError: false, errorDetails: '' };}static getDerivedStateFromError(error) {return { hasError: true, errorDetails: error.message };}componentDidCatch(error, errorInfo) {console.error('Captured runtime error in child subtree:', error, errorInfo);}render() {if (this.state.hasError) {return (<div role="alert" className="error-fallback"><h2>Something crashed</h2><pre>{this.state.errorDetails}</pre></div>);}return this.props.children;}}
react
Breakdown
1
export class SafeErrorBoundary extends Component {
Declares an OOP class component extending the base React.Component class.
2
static getDerivedStateFromError(error) {
Static class lifecycle method that transforms a thrown child exception into fallback state.
3
componentDidCatch(error, errorInfo) {
Instance lifecycle method invoked after an error is thrown to handle side effects and logging.
4
return this.props.children;
Renders nested JSX hierarchy normally when no unhandled render errors have occurred.