Error Boundaries in Reactjs
Blog React Error Boundary in Reactjs

Have you ever faced a problem where one error will crash whole the app.
In Reactjs if a component got an error then by default component tree of the error is displayed on the web page to display a custom fallback UI Reactjs introduced the concept of error boundaries .

In Reactjs a single javascript error can break whole the app. To solve this issue  React 16 introduces a new concept of an “error boundary”.

What is error boundaries

Error boundaries are nothing but a simple React component which catch any JavaScript error in there child tree, log the error and display a custom fallback UI instead of displaying old component tree on the web page.

Error boundaries can catch error from these places

  • Render method.
  • Lifecycle methods.
  • Constructor method.

Error boundaries can not catch error from these places

  • Error thrown in Error boundary component itself instead of there child.
  • Server side rendering (SSR)
  • Async code i.e setTimeout etc
  • Event Handlers

How to use Error Boundary in Reactjs

Any Component which can have either one or both of the lifecycle methods. Those lifecycle methods are:

We will create a ErrorBoundary Component which gonna have only one life cycle method i.e static getDerivedStateFromError() and it will gonna set a error state to true in case any error found and we can display our custom error boundary UI.

static getDerivedStateFromError()

Example of error boundary

Blog React ErrorBoundary Component
Blog React ErrorBoundary Component

We gonna wrap our ErrorBoundary Component to our wrap App so that we can catch error.

Blog Wrap App with ErrorBoundary
Error Boundaries in Reactjs
Blog Wrap App with ErrorBoundary

To see the fallback UI we gonna create an error manually in our App.

App with error
Blog React App with Error

Now we can see a custom fallback UI instead of the component tree.

In case you are using react-create-app you are going to see a overlay of error stack in development mode on top of fallback UI.

Edit Error Boundaries in Reactjs

Checkout best UI library for React here.

Categories: Reactjs

3 Comments

How to use axios with Reactjs - Blog React · January 20, 2020 at 3:46 am

[…] If you want to learn about error boundaries in the reactjs you can learn here. […]

Advanced concepts that you should know in React - Blog React · February 14, 2020 at 3:52 am

[…] Error Boundaries […]

How to use error boundary using Hooks in React - Blog React · February 19, 2020 at 3:33 am

[…] Error Boundary in Class Components […]

Comments are closed.