Hint
Class component wrapping the tree — catches render errors and shows fallback UI instead of blank screen
Error Boundaries catch JavaScript errors during rendering, in lifecycle methods, and in constructors of child components. They must be class components (no hook equivalent yet).
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null };
}
// Render phase — update state to show fallback
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
// Commit phase — log error to monitoring service
componentDidCatch(error, info) {
logErrorToSentry(error, info.componentStack);
}
render() {
if (this.state.hasError) {
return this.props.fallback ?? Something went wrong.
;
}
return this.props.children;
}
}
// Usage — wrap features, not the entire app
function App() {
return (
}>
}>
);
}
// react-error-boundary library — hook-friendly wrapper
import { ErrorBoundary } from 'react-error-boundary';