React Shorts: The ErrorBoundary Component


The ErrorBoundary is a class component in React to catch Errors that happen in your components. Yes - you read that right. The component is only available as a class component thus far and cannot be created via the function syntax. Too bad, but it's really useful so we just have to deal with that.

Use the React ErrorBounday to prevent an error from breaking your entire app

The ErrorBoundary component acts like a try {} catch {}-block wrapped around your components. More specifically Reacts ErrorBoundary catches all errors that happen inside of the component tag. All Errors happening in its child component tree are caught and dealt with.

The Classic: ErrorBoundary as a class

Check the details about the class component in the React Docs. Here is a quick rundown.

The class catches an error and displays a fallback component to gracefully inform the user about a problem and to scope the error to a specific area in our application. This is done using the following techniques:

  • 2 lifecycle methods: getDerivedStateFromError() to update state to show the fallback component and componentDidCatch() to log any errors to some reporting service
  • render method: Component render method to render the fallback component, if the error-state is set, otherwise just return the children

The Modern: ErrorBoundary from react-error-boundary

Since we all fell in love with the new hooks-API since v16.8 we prefer function over classes and composition over inheritance. Therefore I'd like to offer an alternative to creating a class component for this. You can use the react-error-boundary package to get the job done.

Import the component and create an ErrorFallback function, which you pass to the component. Here is a demonstration of the components API taken from the packages README.md.

import {ErrorBoundary} from 'react-error-boundary'

function ErrorFallback({error, resetErrorBoundary}) {
  return (
    <div role="alert">
      <p>Something went wrong:</p>
      <pre>{error.message}</pre>
      <button onClick={resetErrorBoundary}>Try again</button>
    </div>
  )
}

const ui = (
  <ErrorBoundary
    FallbackComponent={ErrorFallback}
    onReset={() => {
      // reset the state of your app so the error doesn't happen again
    }}
  >
    <ComponentThatMayError />
  </ErrorBoundary>
)

Caveat: Catch ErrorBoundary Errors with ErrorBoundaries - wait what?

Remember: ErrorBoundary components catch only errors in components below them. Errors in themselves are caught by the next higher ErrorBoundary!