Performance: Why error boundaries prevent app crashes
This concept affects the app's interaction responsiveness and visual stability by preventing full app crashes during runtime errors.
class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, errorInfo) { // You can log the error here } render() { if (this.state.hasError) { return <div>Something went wrong.</div>; } return this.props.children; } } function App() { return <ErrorBoundary><ComponentThatMayThrow /></ErrorBoundary>; }
function App() {
return <ComponentThatMayThrow />;
}
// No error boundary wrapping the component| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No error boundary | Full app unmount and remount | Multiple reflows due to full layout recalculation | High paint cost due to blank screen and re-render | [X] Bad |
| With error boundary | Only fallback UI updates | Single reflow limited to fallback area | Low paint cost with stable layout | [OK] Good |
ErrorBoundary that returns fallback UI.ErrorBoundary returning JSX fallback UI.export function ErrorBoundary() {
return <div>Oops! Something went wrong.</div>;
}
export default function Component() {
throw new Error('Crash');
return <div>Hello</div>;
}ErrorBoundary function returns fallback UI text 'Oops! Something went wrong.' which will display instead.export function ErrorBoundary() {
console.log('Error caught');
}Pass the test and this pattern moves unknown