javascript / beginner
Snippet
Graceful UI Crash Handling via Class Error Boundary
Error Boundaries are React components that catch JavaScript runtime errors anywhere in their child component tree, log those errors, and display a fallback UI instead of crashing the whole application.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class SafeZone extends React.Component {state = { hasError: false };static getDerivedStateFromError(error) {return { hasError: true };}render() {if (this.state.hasError) {return <h2>Something went wrong. Please try again.</h2>;}return this.props.children;}}
react
Breakdown
1
state = { hasError: false };
Initializes the component state with a boolean tracking whether an error occurred.
2
static getDerivedStateFromError(error) {
Lifecycle method that updates state to render fallback UI after an uncaught error in a child component.
3
if (this.state.hasError) {
Checks error state during render to conditionally display the user-friendly fallback screen.
4
return this.props.children;
Renders the normal child components if no error has occurred.