1.

What are error boundaries?

Answer»

INTRODUCED in 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?

  1. Render phase
  2. Inside a lifecycle method
  3. 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 =&GT; counterValue = prevState+1);}render(){ if(this.state.counter === 2){ throw NEW Error('Crashed'); } return( <div> <button onClick={this.incrementCounter}>Increment Value</button> <p>Value of counter: {this.state.counterValue}</p> </div> )}}

In the code above, when the counterValue equals 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 the 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 <h4>Something went wrong</h4> } 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 the error boundary, we can render the CounterComponent in the following way:

<ErrorBoundary> <CounterComponent/></ErrorBoundary>


Discussion

No Comment Found