React 16: Error Boundaries and Happier Developers

Manuel Palma
2 min readJul 27, 2017

--

Yesterday the public beta of React 16 became available to developers. The new version of the popular framework comes with some new features and a completely rewritten core. One great new built-in that caught my eye (and probably of most developers') is the introduction of Error Boundaries.

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.

Herb photo credit

Basically, class components have now a new lifecycle method, componentDidCatch, which is meant to be an isolation boundary for errors that are produced by children and grandchildren components. Taking advantage of this operation, developers can plan fallback components and logics preventing the app to fully take down.

Code please:

Let’s examine the code. I declared a class-based component and a property errorFound to false in the initial state. Because the code inside componentDidCatch is executed if an error occurs from children, I call setState to warn the component: ”Hey! Your sons are breaking, you will crash”, forcing a new render which returns the safe MyFallbackComponent

As you can see, with just a few lines of code, we can be quieter developers. But. One more thing; do I need to write it everywhere? Of course not, and you already know the answer:

High Order Component ❤

And now we can apply that to all components we want to keep safe

Final tip: of course if you, like me, prefer to write functional components anytime you can, all this above is obviously applicable to your smart comps.

Worth mentioning: React team did also a huge work on the errors emitted. You will be surprised to see how less cryptic they are. This is the error showed by the console for the code upon:

React caught an error thrown by one of your components. You should fix this error in your code. React will try to recreate this component tree from scratch using the error boundary you provided, App.

How lovely is that? ❤

If this article helped, please hit the heart on the left and feel free to share it.

--

--