Understanding Error Handling in React with react-error-boundary

Prathap
2 min readMar 16, 2024

react-error-boundary is a feature introduced in React 16 that provides a way to handle errors that occur during the rendering phase of a React component tree.

In React, if an error occurs during rendering, it can potentially break the entire UI tree, leaving the application in an inconsistent state. Traditionally, React applications would handle errors using try-catch blocks or error boundaries, which are higher-order components that wrap around components to catch errors occurring in their children.

  • react-error-boundary is a built-in error boundary component provided by React.
  • It allows you to define a boundary around a part of your UI and specify how to handle errors within that boundary.
  • When an error occurs within the component tree that is wrapped by ErrorBoundary, it will catch the error and display a fallback UI instead of crashing the entire application.
  • This helps in isolating errors and prevents them from propagating up to higher levels of the component tree.

Here’s a basic example of how you can use react-error-boundary:

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

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

function MyComponent() {
throw new Error('Error occurred in MyComponent');
}

function App() {
return (
<ErrorBoundary FallbackComponent={ErrorFallback} onReset={() => window.location.reload()}>
<MyComponent />
</ErrorBoundary>
);
}

In this example,

  • MyComponent throws an error intentionally.
  • This error is caught by the ErrorBoundary component, which renders the ErrorFallback component instead of crashing the entire application.
  • The ErrorFallback component displays an error message and provides an option to try again.
  • When the user clicks the “Try again” button, the onReset handler is triggered, which in this case reloads the page to reset the application state.

--

--