Tuesday, April 10, 2018

Error boundaries in React v16

React v16.0 provides better error handling, prior to react v16.0 if a component throws an exception then the entire application will crash and the only way to recover is 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.

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  componentDidCatch(error, info) {
    // Display fallback UI
    this.setState({ hasError: true });
    // You can also log the error to an error reporting service
    logErrorToMyService(error, info);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}


Then you can use it as a regular component:

<ErrorBoundary>
  <MyWidget />
</ErrorBoundary>

Search Flipkart Products:
Flipkart.com

No comments: