1.

Explain the Error boundaries in React 16.3?

Answer»

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 component tree that crashed.

A class component becomes an error boundary if it defines either (or both) of the lifecycle methods static getDerivedStateFromError() or componentDidCatch(). Updating state from these lifecycles lets you capture an unhandled JavaScript error in the below tree and display a fallback UI.

static getDerivedStateFromError()
This lifecycle is invoked after an error has been thrown by a component. It receives the error that was thrown as a parameter and should return a value to update state.

As it is called during the render phase so side-effects like this.setState are not allowed.

componentDidCatch()
This lifecycle is invoked after an error has been thrown by a descendant component. It receives two parameters:

  • error - The error that was thrown.
  • INFO - An object with a componentStack key containing information about the component which threw the error.

As it is called during the commit phase so side-effects like this.setState are allowed.

Below is the example where we DEFINE a component called ErrorBoundary

class ErrorBoundary extends React.Component {  constructor(props) {    super(props);    this.state = { hasError: false };  }  static getDerivedStateFromError(error) {    // Update state so the next render will SHOW the fallback UI.    return { hasError: true };  }  componentDidCatch(error, info) {    logComponentStackToMyService(info.componentStack);  }  render() {    if (this.state.hasError) {      return <H1>Something went wrong.</h1>;    }    return this.props.children;  } }

After this we need to wrap any component with it and try will work as the classic try..catch block.

<ErrorBoundary>  <ProductCard /> </ErrorBoundary>


Discussion

No Comment Found