ReactJS :: Error boundaries

No matter how well a project is put together, errors will still find a way in. These can happen in very specific circumstances, be hard to diagnose and leave the application in an unstable state – an absolute nightmare for both users and developers.

React v16 was released back in September 2017. As part of that update, any unhandled errors would now unmount the entire application. To counter this, the concept of error boundaries was introduced. When an error occurs within a component, it will bubble up through its parents until it either hits the root of the application where it will unmount, or finds a component that will handle the error. The idea of the error boundary is a generic component that takes care of the errors for its children.

componentDidCatch(error, info) {
  this.setState({ error: error.message });
render() {
  return this.state.error ? <ErrorDisplay/> : this.props.children;

By hooking into a new lifecycle method, the error can be stored in state and replace the child contents. This effectively ring-fences this branch of the application off from the rest.

The boundaries work like try/catch blocks. They can be nested inside one another without issue, but any errors that occur within them will be caught by the next boundary up. It’s best they are kept as simple as possible.

Leave a Reply

Your email address will not be published. Required fields are marked *