javascript / beginner
Snippet
Catching Render Failures with Class Error Boundaries
Error boundaries are React class components that catch JavaScript errors anywhere in their child component tree. Implementing getDerivedStateFromError updates state to render a fallback UI, while componentDidCatch logs error details without crashing the entire app.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import React from 'react';class SafeErrorBoundary extends React.Component {state = { hasError: false };static getDerivedStateFromError(error) {return { hasError: true };}componentDidCatch(error, errorInfo) {console.error('Captured UI failure:', error, errorInfo);}render() {if (this.state.hasError) {return <h2>Something went wrong while displaying this section.</h2>;}return this.props.children;}}
react
Breakdown
1
class SafeErrorBoundary extends React.Component {
Defines an object-oriented React component capable of implementing error lifecycle methods.
2
static getDerivedStateFromError(error) {
Static lifecycle method called after an error is thrown, returning an updated state to show fallback UI.
3
componentDidCatch(error, errorInfo) {
Lifecycle method used to log captured exception details or send them to an error tracking service.
4
if (this.state.hasError) {
Evaluates whether an error was encountered to conditionally display the recovery message.
5
return this.props.children;
Renders wrapped child components normally when no error is present.