Tuesday, August 21, 2018

React Component Lifecycle - componentDidCatch

The componentDidCatch life-cycle method is used to create special Error Boundary components. Prior to react v16.0 there was not structured way of error handling, if a component throws an exception then the application will crash and we might have to refresh the page.

To overcome this React v16.0 introduces error boundaries. Error boundaries are special components which catch errors in its child component hierarchy and display a custom error / fallback UI. Error boundaries handle any errors in the render(), constructor or any of the component life cycle methods in its child component hierarchy.

React error boundary components are those which implement the componentDidCatch() life-cycle method, when any of its child component throws an exception it is caught in them method and allows us to display a fallback UI.

A React class with error boundaries can only catch errors in the components below them in the tree. An error boundary can’t catch an error within itself. Error boundary components behave like catch {} block, they can capture exceptions in the try {} but cannot capture exceptions in the catch {} block itself.

While implementing error boundary components, think about implementing try {} / catch {} blocks in a normal application. We can have a root Error boundary component encapsulating the whole application, so that any un-handled exception in the application will be captured in the root error boundary component. Also we can have specific error boundaries for components which are complex and error prone, this way we can have a more detailed logging and custom Fallback UI for these components.

Below is the syntax for componentDidCatch

componentDidCatch(error, info) {
    // Log error messages and display fallback UI
}

Search Flipkart Products:
Flipkart.com

No comments: