Error Boundaries
Error boundaries are components that catch JavaScript errors in their child component tree, log them, and display a fallback UI instead of crashing the whole app.
Error boundaries must currently be implemented as class components, using `static getDerivedStateFromError` and/or `componentDidCatch`.
Implementing one
Define a class with `static getDerivedStateFromError(error)` to update state, and `componentDidCatch(error, info)` to log details. Render a fallback when an error was caught.
Usage
Wrap parts of your tree that might fail (like a widget fetching data) with `<ErrorBoundary>{children}</ErrorBoundary>` to contain failures.
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, info) {
console.error(error, info);
}
render() {
if (this.state.hasError) return <h2>Something went wrong.</h2>;
return this.props.children;
}
}Something went wrong. (shown if a child throws)The boundary catches errors in children and renders a fallback UI.
Key points
- Error boundaries catch rendering errors in their child tree.
- They must currently be class components.
- getDerivedStateFromError updates state to show a fallback UI.
- componentDidCatch is used for logging error details.
