javascript / beginner
Snippet
Catching Render Crashes with Class Error Boundaries
React error boundaries are class components that implement getDerivedStateFromError or componentDidCatch. They catch JavaScript errors in their child component tree, preventing the entire UI from crashing and displaying a fallback message instead.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import React, { Component } from 'react';class ErrorBoundary extends Component {state = { hasError: false };static getDerivedStateFromError() {return { hasError: true };}render() {if (this.state.hasError) {return <h1>Something went wrong.</h1>;}return this.props.children;}}export default ErrorBoundary;
react
Breakdown
1
class ErrorBoundary extends Component {
Defines an object-oriented class component inheriting from React.Component.
2
static getDerivedStateFromError() {
Lifecycle method invoked after an error is thrown in a child; returns new state to trigger a fallback render.
3
return { hasError: true };
Updates the component state indicating an error occurred.
4
return this.props.children;
Renders nested child components normally when no error is present.