Learn

Typically error boundary components are created once and then used throughout the entire application where needed. Once the error boundary component has been set up, there isn’t much need to modify its code. As a result, it’s not common for programmers to create their own ErrorBoundary components in the first place. Instead, they will often turn to implementations such as the popular react-error-boundary package.

This package exports an ErrorBoundary component that does all of what our ErrorBoundary component can do plus more! To replicate the basic fallback UI behavior of our own custom ErrorBoundary component, we could write:

import { ErrorBoundary } from 'react-error-boundary'; function ErrorFallback() { return ( <div> <h2>An error was detected!!</h2> </div> ); } function App() { return ( <ErrorBoundary FallbackComponent={ErrorFallback}> <MyComponent /> </ErrorBoundary> ); }

In this example, we:

  • Import the ErrorBoundary component from 'react-error-boundary'.
  • Define an ErrorFallback() component with UI to render if the ErrorBoundary catches an error.
  • Render the ErrorBoundary with our component nested inside.
  • Pass a FallbackComponent={ErrorFallback} prop to ErrorBoundary. When the ErrorBoundary catches an error, the ErrorFallback component renders instead!

At this point, this ErrorBoundary doesn’t have any logging or resetting behavior, but we’ll get to that in the next exercise. For now, let’s add the basic ErrorBoundary to the lightswitch application!

Instructions

1.

We’ve reset the application to its original state when we began the lesson. Currently none of the <LightSwitch> components are protected with an error boundary. Let’s fix that, this time using react-error-boundary!

First, import ErrorBoundary from 'react-error-boundary' (we’ve already installed the package for you).

2.

Next, we will wrap our <LightSwitch> components in separate error boundaries:

  • Wrap the first two <LightSwitch> components in one ErrorBoundary.
  • Wrap the third <LightSwitch> in another ErrorBoundary.
  • Leave the fourth <LightSwitch> unprotected.

For each ErrorBoundary, pass a FallbackComponent prop whose value is the ErrorFallback component that has been provided for you.

Save your code and test out the application. You should have working error boundaries for the first three light switches!

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?