javascript / intermediate
Snippet
Handling Component Render Exceptions with Class-Based Error Boundaries
React requires class components to implement Error Boundaries, as hooks cannot catch lifecycle rendering errors. `getDerivedStateFromError` synchronously updates state to display a fallback UI, while `componentDidCatch` handles side effects like remote error logging.
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
import React, { Component } from 'react';class SafeBoundary extends Component {constructor(props) {super(props);this.state = { hasError: false, error: null };}static getDerivedStateFromError(error) {return { hasError: true, error };}componentDidCatch(error, errorInfo) {console.error('Captured runtime error:', error, errorInfo);}render() {if (this.state.hasError) {return (<div role="alert" className="error-card"><h3>Something went wrong.</h3><p>{this.state.error?.message}</p></div>);}return this.props.children;}}export default SafeBoundary;
react
Breakdown
1
static getDerivedStateFromError(error) {
Static lifecycle method triggered after a child component throws an error during rendering.
2
return { hasError: true, error };
Returns a new state object to render the fallback UI in the next render pass.
3
componentDidCatch(error, errorInfo) {
Lifecycle hook for side effects such as logging the error and stack trace to monitoring services.