Error Boundaries in React 16

Vivek Nayyar
HackerNoon.com

--

React 16 is here and it brings lots of exciting changes. One of the features that got me excited is better error handling. Previously, runtime errors during rendering could put React in a broken state.

With React 16, instead of unmounting the whole app every time there’s an error, you can use error boundaries. Think of error boundaries like try-catch statements, but for React components.

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 crashed component tree.

A class component becomes an error boundary if it defines a new lifecycle method called componentDidCatch(error, info).

With error boundaries, even if one of your component’s results in an error, the entire react app would not get unmounted and instead only the erroneous component would display a fallback UI and the entire app would still be fully functional.

To demonstrate the usage of an error boundary in a React App, we would be taking an example of an e-commerce website which has a product listing page to display what all products are available for sale.

The final page would look something like this:-

--

--