By default, an uncaught JavaScript error inside a single React component unmounts the entire application and leaves users staring at a blank screen. React Error Boundaries catch runtime errors during rendering, inside lifecycle methods, and in constructors of child trees, displaying a clean fallback UI instead.
Error Boundaries must still be written as class components because React has not added a built-in hook equivalent for getDerivedStateFromError and componentDidCatch. You can write one reusable boundary class or install the popular react-error-boundary package.
import { Component } from 'react';
export class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, info) {
console.error('Widget crash:', error, info.componentStack);
}
render() {
if (this.state.hasError) {
return (
<div role="alert" className="error-fallback">
<h3>Unable to load this section.</h3>
<button type="button" onClick={() => this.setState({ hasError: false })}>
Retry
</button>
</div>
);
}
return this.props.children;
}
}
Wrap risky widgets—like charts, third-party embeds, or markdown previewers—in their own <ErrorBoundary>. If the chart throws an exception, the navigation bar and sidebar keep working normally.
onClick, onSubmit): React does not catch errors inside click handlers; use normal try / catch blocks there.setTimeout callbacks, and fetch failures must be handled with try / catch or state error flags.Yes. Resetting { hasError: false } inside state re-renders the children, letting users recover from transient rendering glitches.
React 19 improves error reporting with onCaughtError and onUncaughtError root options in createRoot, deduplicating noisy console stacks in development.
Include one top-level boundary as a safety net, plus smaller boundaries around independent panels so one broken widget never hides the entire page.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With