Showing posts with label componentDidCatch. Show all posts
Showing posts with label componentDidCatch. Show all posts

Tuesday, August 21, 2018

componentDidCatch example

The componentDidCatch life-cycle method is invoked when an exception is thrown in its child component hierarchy. Components which implement componentDidCatch are called Error Boundary components. These components act as catch {} blocks to capture exceptions.

The following example has 3 components
ErrorBoundaryComponent - Implements componentDidCatch, acts as a catch {} block to capture errors in child components.
ChildComponent - Actual UI component, encapsulated in ErrorBoundaryComponent
RootComponent - This is the bootstrap component which launches the application.

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.