Error handling in React 16

If you have built a React app at any point in your programming career, you probably have experienced an error at some point that was cryptic and did not provide any meaningful context on what actually happened.

That meant error occured at some point in the application and our React component did not handle the error gracefully.

A JavaScript error in a part of the UI shouldn’t break the whole app. To solve this problem for React users, React 16 introduces a new concept of an “error boundary”.

try/catch only works for imperative code, but React components are declarative.

Since early React development (≤15), it was common for a child component throwing an error to break the entire application and React did not provide a way to handle them gracefully in components. That’s why Error Boundaries are a good thing.

Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.

In React 16 we have a built-in function called componentDidCatch to deal with this uncaught errors. Let’s take a look:

Error Boundaries in React

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.

🧐 First all, important to know that Error Boundaries will not catch errors in:

  1. Event handlers. ** — Use a try / catch block instead within event handlers.
  2. Asynchronous code (e.g. setTimeout or requestAnimationFrame callbacks)
  3. Server side rendering
  4. Errors within the Error Boundary Component. — You cannot save others if you cannot save yourself first.

After that, let’s recall a new lifecycle method called

componentDidCatch(error, info)

😀 It works in the same way that Javascript’s try/catch works.

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.

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store