We use cookies to enhance your experience on the site
CodeWorlds

react-error-boundary - A Modern Library

Creating Error Boundaries from scratch requires writing class components, which in the age of hooks can feel archaic. Fortunately, the

react-error-boundary
library exists, which greatly simplifies working with error handling.

Installation and Basic Usage

1npm install react-error-boundary

The library provides a ready-made

ErrorBoundary
component with many useful features:

1import { ErrorBoundary } from 'react-error-boundary';
2
3function ErrorFallback({ error, resetErrorBoundary }) {
4  return (
5    <div className="error-panel">
6      <h2>Module failure!</h2>
7      <p>{error.message}</p>
8      <button onClick={resetErrorBoundary}>
9        Restart module
10      </button>
11    </div>
12  );
13}
14
15function App() {
16  return (
17    <ErrorBoundary
18      FallbackComponent={ErrorFallback}
19      onError={(error, info) => {
20        // Log to monitoring service
21        console.error('Logged error:', error);
22      }}
23      onReset={() => {
24        // Reset application state after fixing the error
25        console.log('Error boundary reset');
26      }}
27    >
28      <SpaceStation />
29    </ErrorBoundary>
30  );
31}

FallbackComponent vs fallback vs fallbackRender

The library offers three ways to define the fallback UI:

1. FallbackComponent (recommended)

1function MyFallback({ error, resetErrorBoundary }) {
2  return (
3    <div>
4      <p>Error: {error.message}</p>
5      <button onClick={resetErrorBoundary}>Try again</button>
6    </div>
7  );
8}
9
10<ErrorBoundary FallbackComponent={MyFallback}>
11  <App />
12</ErrorBoundary>

2. fallback (simple JSX)

1<ErrorBoundary fallback={<p>Something went wrong!</p>}>
2  <App />
3</ErrorBoundary>

3. fallbackRender (render prop)

1<ErrorBoundary
2  fallbackRender={({ error, resetErrorBoundary }) => (
3    <div>
4      <p>{error.message}</p>
5      <button onClick={resetErrorBoundary}>Reset</button>
6    </div>
7  )}
8>
9  <App />
10</ErrorBoundary>

The useErrorBoundary Hook

One of the most powerful tools in the library - the

useErrorBoundary
hook allows you to programmatically trigger errors in an Error Boundary from event handlers and asynchronous code!

1import { useErrorBoundary } from 'react-error-boundary';
2
3function DataFetcher() {
4  const { showBoundary } = useErrorBoundary();
5  const [data, setData] = useState(null);
6
7  const fetchData = async () => {
8    try {
9      const response = await fetch('/api/missions');
10      if (!response.ok) {
11        throw new Error('Failed to fetch mission data');
12      }
13      const result = await response.json();
14      setData(result);
15    } catch (error) {
16      // Pass the error to the nearest Error Boundary!
17      showBoundary(error);
18    }
19  };
20
21  return (
22    <div>
23      <button onClick={fetchData}>Fetch mission data</button>
24      {data && <p>Missions: {data.length}</p>}
25    </div>
26  );
27}

resetKeys - Automatic Reset

You can configure

resetKeys
- a list of values whose change will automatically reset the Error Boundary:

1function App() {
2  const [selectedPlanet, setSelectedPlanet] = useState('Mars');
3
4  return (
5    <ErrorBoundary
6      FallbackComponent={ErrorFallback}
7      resetKeys={[selectedPlanet]}
8      onReset={() => {
9        // Cleanup after reset
10        console.log('Boundary reset - new planet:', selectedPlanet);
11      }}
12    >
13      <PlanetDetails planet={selectedPlanet} />
14    </ErrorBoundary>
15  );
16}
17// When the user changes the planet, the Error Boundary will automatically reset

Nested Error Boundaries

You can nest multiple Error Boundaries for different levels of handling:

1<ErrorBoundary FallbackComponent={AppCrashScreen}>
2  <Header />
3  <ErrorBoundary FallbackComponent={SectionError}>
4    <MissionControl />
5  </ErrorBoundary>
6  <ErrorBoundary FallbackComponent={SectionError}>
7    <CrewPanel />
8  </ErrorBoundary>
9</ErrorBoundary>

If an error occurs in

MissionControl
, it will be caught by the inner
ErrorBoundary
. If the inner one itself throws an error, it will be caught by the outer one.

Comparison: Custom Error Boundary vs react-error-boundary

| Feature | Custom (class) | react-error-boundary | |---------|----------------|---------------------| | Reset | Manually implemented | Built-in (resetErrorBoundary) | | Auto-reset | None | resetKeys | | Hook | None | useErrorBoundary | | Logging | Manual | Built-in (onError) | | Async errors | Doesn't catch | showBoundary() | | Boilerplate | A lot | Minimal |

The key advantage of the library is the

useErrorBoundary
hook -- it allows catching errors from event handlers and asynchronous code, which native Error Boundaries cannot do. In practice, if you're building a serious production application,
react-error-boundary
is the industry standard -- just like standardized safety systems on spacecraft.

Go to CodeWorlds