Security News
vlt Debuts New JavaScript Package Manager and Serverless Registry at NodeConf EU
vlt introduced its new package manager and a serverless registry this week, innovating in a space where npm has stagnated.
react-error-boundary
Advanced tools
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.
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);
}"}
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 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.
Reusable React error boundary component. Supports all React renderers (including React DOM and React Native).
# npm
npm install react-error-boundary
# yarn
yarn add react-error-boundary
ErrorBoundary
componentWrap an ErrorBoundary
around other React components to "catch" errors and render a fallback UI. The component supports several ways to render a fallback (shown below).
Note
ErrorBoundary
is a client component. You can only pass props to it that are serializeable or use it in files that have a"use client";
directive.
ErrorBoundary
with fallback
propThe simplest way to render a default "something went wrong" type error message.
"use client";
import { ErrorBoundary } from "react-error-boundary";
<ErrorBoundary fallback={<div>Something went wrong</div>}>
<ExampleApplication />
</ErrorBoundary>
ErrorBoundary
with fallbackRender
prop"Render prop" function responsible for returning a fallback UI based on a thrown value.
"use client";
import { ErrorBoundary } from "react-error-boundary";
function fallbackRender({ error, resetErrorBoundary }) {
// Call resetErrorBoundary() to reset the error boundary and retry the render.
return (
<div role="alert">
<p>Something went wrong:</p>
<pre style={{ color: "red" }}>{error.message}</pre>
</div>
);
}
<ErrorBoundary
fallbackRender={fallbackRender}
onReset={(details) => {
// Reset the state of your app so the error doesn't happen again
}}
>
<ExampleApplication />
</ErrorBoundary>;
ErrorBoundary
with FallbackComponent
propReact component responsible for returning a fallback UI based on a thrown value.
"use client";
import { ErrorBoundary } from "react-error-boundary";
function Fallback({ error, resetErrorBoundary }) {
// Call resetErrorBoundary() to reset the error boundary and retry the render.
return (
<div role="alert">
<p>Something went wrong:</p>
<pre style={{ color: "red" }}>{error.message}</pre>
</div>
);
}
<ErrorBoundary
FallbackComponent={Fallback}
onReset={(details) => {
// Reset the state of your app so the error doesn't happen again
}}
>
<ExampleApplication />
</ErrorBoundary>;
onError
"use client";
import { ErrorBoundary } from "react-error-boundary";
const logError = (error: Error, info: { componentStack: string }) => {
// Do something with the error, e.g. log to an external API
};
const ui = (
<ErrorBoundary FallbackComponent={ErrorFallback} onError={logError}>
<ExampleApplication />
</ErrorBoundary>
);
useErrorBoundary
hookConvenience hook for imperatively showing or dismissing error boundaries.
React only handles errors thrown during render or during component lifecycle methods (e.g. effects and did-mount/did-update). Errors thrown in event handlers, or after async code has run, will not be caught.
This hook can be used to pass those errors to the nearest error boundary:
"use client";
import { useErrorBoundary } from "react-error-boundary";
function Example() {
const { showBoundary } = useErrorBoundary();
useEffect(() => {
fetchGreeting(name).then(
response => {
// Set data in state and re-render
},
error => {
// Show error boundary
showBoundary(error);
}
);
});
// Render ...
}
A fallback component can use this hook to request the nearest error boundary retry the render that original failed.
"use client";
import { useErrorBoundary } from "react-error-boundary";
function ErrorFallback({ error }) {
const { resetBoundary } = useErrorBoundary();
return (
<div role="alert">
<p>Something went wrong:</p>
<pre style={{ color: "red" }}>{error.message}</pre>
<button onClick={resetBoundary}>Try again</button>
</div>
);
}
withErrorBoundary
HOCThis package can also be used as a higher-order component that accepts all of the same props as above:
"use client";
import {withErrorBoundary} from 'react-error-boundary'
const ComponentWithErrorBoundary = withErrorBoundary(ExampleComponent, {
fallback: <div>Something went wrong</div>,
onError(error, info) {
// Do something with the error
// E.g. log to an error logging client here
},
})
// Can be rendered as <ComponentWithErrorBoundary {...props} />
This blog post shows more examples of how this package can be used, although it was written for the version 3 API.
FAQs
Simple reusable React error boundary component
The npm package react-error-boundary receives a total of 2,673,702 weekly downloads. As such, react-error-boundary popularity was classified as popular.
We found that react-error-boundary demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
vlt introduced its new package manager and a serverless registry this week, innovating in a space where npm has stagnated.
Security News
Research
The Socket Research Team uncovered a malicious Python package typosquatting the popular 'fabric' SSH library, silently exfiltrating AWS credentials from unsuspecting developers.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.