In React 16, Error Boundaries were introduced as a way to handle and manage errors occurring during the rendering process. Error boundaries are React components that act as parents for their child components, catching any errors their child components might throw during rendering, lifecycle methods, or constructors.
With error boundaries, a single component error won't cause the entire application to crash. The error boundary component provides a fallback UI when an error occurs within the component wrapped in an error boundary.
Whenever an error occurs in a child component, componentDidCatch(error, info) is called. Two arguments are passed to this method: error, which represents the actual error thrown, and info, which contains additional information about the component causing the error.
Whenever an error occurs, static getDerivedStateFromError() is called to update the component's state. The process receives an error object as an argument and returns a new state object.
In order to handle errors in a component hierarchy, you wrap the hierarchy with an error boundary component. The components can either be wrapped individually or as higher-order components (HOCs) with multiple components wrapped together.
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
// You can also log the error to an error reporting service
console.error(error, info);
}
render() {
if (this.state.hasError) {
return <div>Something went wrong.</div>;
}
return this.props.children;
}
}
<ErrorBoundary>
<YourComponent />
</ErrorBoundary>
In this way, the error boundary will catch an error within YourComponent or any of its child components, update its state, and render the fallback UI instead of crashing the whole application. The error boundaries they surround and their descendants only catch errors within those components. It does not catch errors in event handlers, asynchronous code (e.g., setTimeout), or on the server.
import React, { Component } from 'react';
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error) {
this.setState({ hasError: true });
console.error(error);
}
render() {
if (this.state.hasError) {
return <div>Something went wrong.</div>;
}
return this.props.children;
}
}
export default ErrorBoundary;
This component renders a fallback UI with an error message that says, "Something went wrong."
<ErrorBoundary>
<YourComponent />
</ErrorBoundary>
The error boundary will catch errors within YourComponent and its descendant components, update its state, and render the fallback UI instead of crash the application when an error occurs.