InterviewSolution
| 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() componentDidCatch()
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> |
|