What is an error boundary?
Error boundaries is the React way to handle errors in your application, making it possible to log them and display a custom page or a message known as Fallback UI instead of a regular error page, which is a total turn off to users.
Error Boundary was introduce in React 16 version.
The idea behind error boundaries is that you can catch error return by your app and report it to your favorite error reporting service (like Sentry), and try to recover if possible.
In simple words: Error boundaries work like a JavaScript catch {} block, but for components.
Why use this approach?
React recommends using an error boundary to provide a better user experience when an error occurs.
By default, if your application throws an error during rendering, React will remove its UI from the screen or a error page like this:
A typical React error without Error boundary.
To prevent this, you can wrap a part of your UI into an error boundary. An error boundary is a special component that lets you display some fallback UI instead of the part that crashed—for example, an error message.
How to implement Error Boundary?
You can write your own error boundary logic is fine, but, this can very expensive and boring. There are many NPM packages to make this work and I'll show how to one. Furthermore, the documentation is very simple to understand.
You can implement error boundaries in react hooks with the help of the react-error-boundary package.
yarn add react-error-boundary
After installing the package in your project, you add the code below:
import {ErrorBoundary} from 'react-error-boundary'
function ErrorFallback({error, resetErrorBoundary}) {
return (
<div role="alert">
<p>Something went wrong:</p>
<pre>{error.message}</pre>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
)
}
const ui = (
<ErrorBoundary
FallbackComponent={ErrorFallback}
onReset={() => {
// reset the state of your app so the error doesn't happen again
}}
>
<ComponentThatMayError />
</ErrorBoundary>
)
It saw! Simple, no?
There are several packages and methods to implement error boundaries. See here: https://blog.logrocket.com/react-error-handling-react-error-boundary/
I encourage you to write your first "error boundary" to understand how it works.
Summary
Handling errors and unexpected events is crucial for any quality application. It’s extremely important to provide a great user experience, even when things doesn’t go as planned.
Error boundaries is a great way to make your application fail gracefully, and even contain errors to parts of your application while the rest continues to work! Write your own, or adopt the react-error-boundary library to do it for you. No matter what you choose, your users will thank you!
Top comments (0)