Well done! You’ve successfully created your own
ErrorBoundary components and you’ve used the popular
react-error-boundary package to keep your application running in the face of errors. Error boundaries are essential defenders of our React applications that allow our users to have the most seamless experience possible.
Let’s recap what we’ve learned so far:
- Error boundaries are React components that wrap sections of a React application, catching runtime errors anywhere in their child component tree. They can render a fallback UI and log errors instead of just showing a blank screen. Error boundaries allow you to recover in the event of an error which leads to a better user experience.
- React components become error boundaries once they implement one (or both) of the lifecycle methods
componentDidCatch(). In order to use these lifecycle methods, the error boundary must be a class component.
static getDerivedStateFromError()lifecycle method receives the thrown
errorvalue and should return the error boundary’s next
this.state. The error boundary’s new
this.statevalue may be used to determine what to render: the fallback UI or the wrapped component tree. The
this.statevalue can be reset to reset the error boundary and its children.
componentDidCatch()lifecycle method is used to log the thrown error. It receives the thrown
errorInfoobject as parameters.
.componentStackproperty containing the history of rendered components that led to the error.
- Typically, Error boundaries are created once and used multiple times throughout the application. It’s common to use third-party error boundary implementations such as
react-error-boundarypackage exports an
<ErrorBoundary>component that can receive the props
onError(which can be assigned a function for logging errors), and
FallbackComponent(which can be assigned a fallback UI component).
- We can provide an inline function for the
FallbackComponentprop to pass additional props to the fallback UI.
- Error boundaries should be kept as close to the source of the error as possible. Common places to use error boundaries are around new features that have not been thoroughly tested.
Congrats again on finishing this lesson!