Performance: Handling runtime errors
This affects user experience responsiveness and visual stability by preventing crashes and layout shifts caused by unhandled errors.
import React from 'react'; class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, errorInfo) { // log the error } render() { if (this.state.hasError) { return <div role="alert">Something went wrong.</div>; } return this.props.children; } } function RiskyChild() { const data = JSON.parse('invalid json'); return <div>{data.name}</div>; } function MyComponent() { return ( <ErrorBoundary> <RiskyChild /> </ErrorBoundary> ); }
function MyComponent() { const data = JSON.parse('invalid json'); return <div>{data.name}</div>; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No error handling | Component unmounts abruptly | Multiple reflows due to layout shifts | High paint cost from UI flicker | [X] Bad |
| Error boundary with fallback UI | Stable DOM with fallback nodes | Single reflow for fallback render | Low paint cost, smooth UI | [OK] Good |
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
console.log('Error caught:', error);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}class MyErrorBoundary extends React.Component {
state = { error: null };
componentDidCatch(error, info) {
this.setState({ error });
}
render() {
if (this.state.error) {
return <div>Error occurred</div>;
}
return this.props.children;
}
}Pass the test and this pattern moves unknown