At this point in your learning journey, you’ve likely come across the try
/catch
block. As the names of the keywords suggest, try
blocks allow programmers to attempt to execute some code. If a runtime error is thrown, catch
blocks intercept and handle the error.
try { thisMightThrowAnError(); } catch (error) { thatsOkWeCanHandleIt(error); }
Backup plans like try
/catch
blocks allow programmers to respond to, and hopefully fix, errors rather than letting them crash the entire application. React uses a similar technique to handle errors within its component tree — error boundary components.
Error boundaries are React components that catch runtime errors anywhere in their child component tree. The error boundary can log those errors and display a backup user-interface (a “fallback UI”) instead of a blank screen. Error boundaries are commonly used around new features that have not been thoroughly tested as they allow you to recover in the event of an error.
We’ll dive deeper into the syntax later, but here’s a quick example of an error boundary component protecting an error-prone component:
<ErrorBoundary FallbackComponent={FallbackUI}> <MyErrorProneComponent /> </ErrorBoundary>
In this lesson, we’ll learn how to build a simple ErrorBoundary
component to protect our application. Then we’ll look at a popular implementation that you can use in your projects rather than having to create it from scratch each time. By the end of this lesson, you will be able to:
- Create an
ErrorBoundary
class component that wraps other components - Use
static getDerivedStateFromError()
to render a fallback UI after an error has been thrown - Use
componentDidCatch()
to log error information - Reset the broken components to a good state
- List examples of which errors that error boundaries can be used for (and those that they can’t be used for)
- Use the
ErrorBoundary
component from thereact-error-boundary
package
Let’s get started!
Instructions
Take a look at the animation provided. Without error boundaries, when a component breaks, the error bubbles up to the root of the application and the entire application crashes. With error boundaries in place, the rest of the application is protected from the error that occurs. Furthermore, a fallback UI component can be rendered.