Introduced in the version 16 of React, Error boundaries provide a way for us to catch errors that occur in the render phase.
What is an error boundary?
Any component which uses one of the following lifecycle methods, is considered an error boundary.
In what places can an error boundary detect an error?
Render phase
Inside a lifecycle method
Inside the constructor
Without using error boundaries:
class CounterComponent extends React.Component{
constructor(props){
super(props);
this.state = {
counterValue: 0
}
this.incrementCounter = this.incrementCounter.bind(this);
}
incrementCounter(){
this.setState(prevState => counterValue = prevState+1);
}
render(){
if(this.state.counter === 2){
throw new Error('Crashed');
}
return(
Value of counter: {this.state.counterValue}
)
}
}
In the code above, when the counterValue equals to 2, we throw an error inside the render method.
When we are not using the error boundary, instead of seeing an error, we see a blank page.
Since any error inside the render method, leads to unmounting of the component.
To display an error that occurs inside the render method, we use error boundaries.
With error boundaries:
As mentioned above, error boundary is a component using one or both of the following methods:
static getDerivedStateFromError and componentDidCatch.
Let’s create an error boundary to handle errors in render phase:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
logErrorToMyService(error, errorInfo);
}
render() {
if (this.state.hasError) {
return
Something went wrong
}
return this.props.children;
}
}
In the code above, getDerivedStateFromError function renders the fallback UI interface when the render method has an error.
componentDidCatch logs the error information to an error tracking service.
Now with error boundary, we can render the CounterComponent in the following way: