Course contentsShow
← React
Lesson 1322 of 2,39633. Error BoundariesFree lesson

Installing and Basic Setup of react-error-boundary

How to add the react-error-boundary package and wrap components with ErrorBoundary for cleaner error handling.

Installing and Basic Setup of react-error-boundary

You'll learn how to install the react-error-boundary package and use its ErrorBoundary component to handle errors more elegantly than writing custom class components.

Why react-error-boundary?

You've learned that error boundaries must be class components with special lifecycle methods like componentDidCatch and getDerivedStateFromError. This is verbose and doesn't fit modern React's functional style. The react-error-boundary package solves this by providing a ready-made ErrorBoundary component you can use declaratively—no classes needed.

Think of it as: Instead of building your own airbag system for every car, you buy a tested, certified airbag off the shelf and install it where needed.

Installation

npm install react-error-boundary

or

yarn add react-error-boundary

Basic Usage

Import and wrap any component that might throw errors:

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

function ErrorFallback({ error }) {
  return (
    <div role="alert">
      <p>Something went wrong:</p>
      <pre>{error.message}</pre>
    </div>
  );
}

function App() {
  return (
    <ErrorBoundary FallbackComponent={ErrorFallback}>
      <MyRiskyComponent />
    </ErrorBoundary>
  );
}

The ErrorBoundary wraps your components just like you've learned with custom boundaries, but handles all the class component boilerplate for you. You simply provide a FallbackComponent to render when errors occur.

What You Get

  • No class components to write — pure functional React
  • Built-in error logging — via onError prop
  • Reset functionality — automatic retry mechanisms
  • TypeScript support — better type safety

Key Takeaway: react-error-boundary eliminates the need to write custom class-based error boundaries by providing a declarative <ErrorBoundary> wrapper component that handles render errors with less code and better developer experience.