Error boundaries in React are the components that catch errors that may occur anywhere in the child components and then log the error and display a fallback UI and prevents the whole component tree from crashing. Error boundaries catch errors during component rendering in lifecycle methods. Only a class component can become an error boundary. A component becomes an error boundary if it defines either (or both) of the lifecycle methods static getDerivedStateFromError()
or componentDidCatch()
. static getDerivedStateFromError()
is used to render a fallback UI after an error has been thrown. componentDidCatch()
is used to log error information.
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// You can also log the error to an error reporting service
logErrorToMyService(error, errorInfo);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
This error boundary can be declared once and used through the app as a regular component.
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>