Catch render errors with an error boundary
Show a fallback instead of a blank screen when a React component throws while rendering, using a class-based error boundary or react-error-boundary.
An error thrown while rendering unmounts the whole React tree unless something catches it. An error boundary is that something, and it still has to be a class component.
import { Component } from 'react';
export class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
componentDidCatch(error, info) {
console.error('Render failed:', error.message, info.componentStack);
}
render() {
if (this.state.error) {
return <p>Something went wrong.</p>;
}
return this.props.children;
}
}import { ErrorBoundary } from './ErrorBoundary.jsx';
import { Chart } from './Chart.jsx';
export function App() {
return (
<ErrorBoundary>
<Chart data={null} />
</ErrorBoundary>
);
}Something went wrong.If Chart throws while rendering with null data, getDerivedStateFromError stores the error and the boundary renders the fallback in place of its children. The rest of the page stays alive. See Catching rendering errors with an error boundary.
Boundaries do not catch errors in event handlers, async code or the server. For those, handle the error where it happens. The react-error-boundary package wraps this pattern in a function component with a reset button.