React Error Boundary: A Guide to Gracefully Handling Errors

Search for a command to run...

Thanks Saran Pariyar
Thanks Prof Gra
Emails are widely used for communication, whether it's expressing thoughts, sharing product information, sending content to newsletter subscribers, sharing event details, and more. Crafting and sending emails isn't straightforward. You have to design...
Every October, the developer community buzzes with Hacktoberfest energy. PRs fly, t-shirts are earned, and GitHub turns green. But here's what nobody talks about: what happens in November? For most contributors, the answer is simple: nothing. The rep...

The debate over AI coding agents is missing the most important factor. It’s not about prompt engineering, it’s about understanding the context window. Developers are divided. One side claims coding agents suck. The other insists you’re just using the...

Learnings from a Research Paper

Lately, I have been working on a feature to capture images from media streams and scale them down to reduce their size. This helps save storage and reduce costs before uploading the images to a storage service. For this, I used Canvas to render the i...

AI helps you do more, but only if you know the basics well enough to tell it what you want.

React revolves around JavaScript, and as the application expands, certain components may become error-prone, leading to a blank page problem. To tackle this, we should incorporate Error Boundaries. These boundaries will display an alternative UI when an error occurs, allowing the user to navigate back or retry. This article will explore how we can gracefully handle errors in React by using error boundaries.
Think of error boundaries in React as safety nets. They're like guardians watching over a group of performers (the components) on a stage (the app). If any performer falls down (a JavaScript error occurs), the safety net (the error boundary) catches them. It then logs what happened and puts up a poster (the fallback UI) until the performer is ready to get back on stage.
React supports two types of components: class-based and functional components. However, if we want to implement an error boundary, we can't do it with a functional component; we need to create a class-based component for the error boundary. But don't worry, the React community is extensive, and many third-party packages are available to help you use a React error boundary component directly instead of creating it yourself.
We will use the react-error-boundary package, which provides an ErrorBoundary component that catches errors and displays the fallback UI. It offers various methods to show the fallback UI.
Let's begin by installing the react-error-boundary as a dependency in our React project.
yarn add react-error-boundary
OR
npm install react-error-boundary
OR
pnpm add react-error-boundary
After installing the dependency, create the fallback component that you want to display when an error occurs.
import React from "react";
import { FallbackProps } from "react-error-boundary";
import ErrorFallbackIcon from "./error-fallback.svg";
const ErrorFallback: React.FC<FallbackProps> = ({
error,
resetErrorBoundary,
}) => {
return (
<div className="error-boundary-fallback-wrapper">
<ErrorFallbackIcon />
<h1>Something went wrong</h1>
<p>{error.message}</p>
<button onClick={resetErrorBoundary}>Home</button>
</div>
);
};
export default ErrorFallback;
The fallback component accepts two props.
error : error object that contains the error message.
resetErrorBoundary : a callback function to reset the error boundary and retry rendering.
Alright, we have the fallback component ready. Now, let's wrap our application with the ErrorBoundary component provided by react-error-boundary.
import React from 'react';
import { ErrorBoundary } from 'react-error-boundary';
import { useHistory } from 'react-router-dom';
import ErrorFallback from './ErrorFallback';
interface Props {
children: React.ReactNode;
}
const App: React.FC<Props> = ({ children }) => {
const history = useHistory();
const handleErrorReset = () => {
history.push("/");
};
return (
<ErrorBoundary FallbackComponent={ErrorFallback} onReset={handleErrorReset}>
{children}
</ErrorBoundary>
);
};
export default App;
The ErrorBoundary component accepts several props, but the important ones are:
FallbackComponent : Fallback component to render when an error occurs.
onReset : callback function to reset the state of the application so that the error doesn't happen again.
Okay, our application is now wrapped with an error boundary. As a regular user, if you interact with the application and encounter an error on a specific page causing a crash, instead of seeing a blank page, you will be directed to a fallback page. This page will display the exact error message and provide you with the option to navigate back.

Implementing error boundaries in React using the react-error-boundary package can help in gracefully handling errors and providing a fallback UI for users when errors occur. By incorporating error boundaries, developers can ensure a better user experience by preventing blank pages and offering options to navigate back or retry.
That's all for this topic. Thank you for reading! If you found this article helpful, please consider liking, commenting, and sharing it with others.