Learn
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
static getDerivedStateFromError()
and/orcomponentDidCatch()
. In order to use these lifecycle methods, the error boundary must be a class component. - The
static getDerivedStateFromError()
lifecycle method receives the thrownerror
value and should return the error boundary’s nextthis.state
. The error boundary’s newthis.state
value may be used to determine what to render: the fallback UI or the wrapped component tree. Thethis.state
value can be reset to reset the error boundary and its children. - The
componentDidCatch()
lifecycle method is used to log the thrown error. It receives the thrownerror
and anerrorInfo
object as parameters.errorInfo
has a.componentStack
property 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-boundary
. - The
react-error-boundary
package exports an<ErrorBoundary>
component that can receive the propsonError
(which can be assigned a function for logging errors), andFallbackComponent
(which can be assigned a fallback UI component). - We can provide an inline function for the
FallbackComponent
prop 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!
Sign up to start coding
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.