What is react-error-boundary?
The react-error-boundary package provides a simple and reusable wrapper component that catches JavaScript errors in their child component tree, logs those errors, and displays a fallback UI instead of the component tree that crashed. It is designed to handle errors that occur during rendering, in lifecycle methods, and in constructors of the whole tree below them.
What are react-error-boundary's main functionalities?
Error Boundary Wrapper
This feature allows you to wrap your components with an ErrorBoundary component. You can specify a FallbackComponent to be displayed when an error is caught, and an onError handler to log or report errors.
{"<ErrorBoundary FallbackComponent={MyFallbackComponent} onError={myErrorHandler}>
<MyWidget />
</ErrorBoundary>"}
useErrorHandler Hook
The useErrorHandler hook can be used within functional components to handle errors. When an error is caught, it can be passed to the handleError function provided by the hook, which will then trigger the nearest error boundary.
{"const handleError = useErrorHandler();
try {
// Some operation that might fail
} catch (error) {
handleError(error);
}"}
Other packages similar to react-error-boundary
react-error-overlay
This package provides an overlay for displaying runtime errors in React applications. It is similar to react-error-boundary in that it helps developers handle errors, but it focuses on providing a development-time overlay that displays errors rather than a production-ready error boundary component.
react-error-guard
React-error-guard is a package that provides error boundary functionality with a focus on simplicity and minimalism. It is similar to react-error-boundary but may have fewer features and a simpler API, which could be beneficial for smaller projects or for developers who prefer a more straightforward approach.
react-error-boundary
Sample reusable React error boundary component for React 16+
The simplest way to use a boundary is to wrap it around any component that may throw an error.
This will handle errors thrown by that component's descendents also.
import ErrorBoundary from 'react-error-boundary';
<ErrorBoundary>
<ComponentThatMayError />
</ErrorBoundary>
You can also react to errors (eg for logging) by providing an onError
callback:
import ErrorBoundary from 'react-error-boundary';
const myErrorHandler = (error: Error, componentStack: string) => {
};
<ErrorBoundary onError={myErrorHandler}>
<ComponentThatMayError />
</ErrorBoundary>
You can also customize the fallback appearance:
const MyFallbackComponent = ({ componentStack, error }) => (
<div/>
)
<ErrorBoundary FallbackComponent={MyFallbackComponent}>
<ComponentThatMayError />
</ErrorBoundary>