| How to Manage State Across Multiple Pages :👈 | 👉:How to Organize a Large React Codebase |
How to Design Error Boundaries in React |
How to Design Error Boundaries in React
1. What Are Error Boundaries in React?
An Error Boundary is a React component that catches JavaScript errors in its child component tree during rendering and displays a fallback UI instead of allowing the entire application section to fail.
For example, consider an e-commerce application with these sections:
- Header
- Product List
- Shopping Cart
- User Profile
Suppose the Product List component throws an error while rendering. Without an Error Boundary, the affected part of the application may fail.
With an Error Boundary, we can display a fallback message such as:
Something went wrong while loading products.
Please try again.
Other sections of the application can continue working if they are outside the failed boundary.
2. Why Do We Need Error Boundaries?
React applications can encounter errors because of:
- Unexpected data returned by components.
- Incorrect property access.
- Rendering errors.
- Third-party component failures.
- Unexpected errors in child components.
Error Boundaries help to:
- Prevent a component rendering failure from affecting unrelated application sections.
- Display a user-friendly fallback interface.
- Provide a recovery option.
- Capture error information for debugging.
- Improve application reliability.
3. How Does an Error Boundary Work?
An Error Boundary works by wrapping other components.
When a descendant component throws an error during rendering, React activates the nearest Error Boundary and displays its fallback UI.
The nearest Error Boundary handles the rendering error. A boundary cannot catch errors thrown by its own fallback UI; an outer boundary may handle those errors.
4. How to Create an Error Boundary
React provides two lifecycle methods used to implement Error Boundaries in class components:
- getDerivedStateFromError(): Updates state so the component can render a fallback UI.
- componentDidCatch(): Receives error information and can be used for logging.
Example:
import React from "react";
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = {
hasError: false
};
}
static getDerivedStateFromError(error) {
return {
hasError: true
};
}
componentDidCatch(error, errorInfo) {
console.error("Error caught:", error);
console.error("Component stack:", errorInfo.componentStack);
}
render() {
if (this.state.hasError) {
return (
<div>
<h2>Something went wrong.</h2>
<p>Please try again later.</p>
</div>
);
}
return this.props.children;
}
}
export default ErrorBoundary;
How this works:
- The Error Boundary starts with
hasError: false. - React renders its child components normally.
- If a descendant throws a rendering error, React calls
getDerivedStateFromError(). - The state changes to
hasError: true. - The fallback UI is displayed.
componentDidCatch()can log the error for debugging.
Important: Error Boundaries are still implemented using class components in React's built-in API. There is no built-in function component equivalent that uses a Hook to catch rendering errors.
5. How to Use an Error Boundary
After creating the Error Boundary, wrap the components that need protection.
Example:
import ErrorBoundary from "./ErrorBoundary";
import ProductList from "./ProductList";
function App() {
return (
<div>
<h1>My Shopping Application</h1>
<ErrorBoundary>
<ProductList />
</ErrorBoundary>
</div>
);
}
export default App;
If ProductList or one of its descendant components throws a rendering error, the Error Boundary displays its fallback UI.
6. Where Should We Place Error Boundaries?
One of the most important design decisions is deciding where to place Error Boundaries.
Avoid placing only one boundary around the entire application if independent sections should be able to recover separately.
For example, consider an e-commerce application:
With this design:
- If ProductList fails, its fallback UI is displayed.
- ShoppingCart can continue working.
- UserProfile can continue working.
- Header and Footer remain outside those boundaries.
Recommended placement:
| Application Area | Recommended Boundary |
|---|---|
| Entire application | Root Error Boundary |
| Dashboard widgets | Individual widget boundaries |
| Product listing | Product section boundary |
| Third-party components | Dedicated boundary |
| Independent page sections | Separate boundaries |
7. Designing a Reusable Error Boundary
Instead of repeating fallback UI in multiple places, create a reusable Error Boundary that accepts a fallback component.
Example:
import React from "react";
class ErrorBoundary extends React.Component {
state = {
hasError: false
};
static getDerivedStateFromError() {
return {
hasError: true
};
}
componentDidCatch(error, errorInfo) {
console.error(error, errorInfo);
}
render() {
if (this.state.hasError) {
return this.props.fallback || (
<h2>Something went wrong.</h2>
);
}
return this.props.children;
}
}
export default ErrorBoundary;
Usage:
function ProductError() {
return (
<div>
<h3>Unable to display products</h3>
<p>Please try again later.</p>
</div>
);
}
function App() {
return (
<ErrorBoundary fallback={<ProductError />}>
<ProductList />
</ErrorBoundary>
);
}
Now the same Error Boundary can be reused for different application sections with different fallback interfaces.
8. Adding a Retry Mechanism
Displaying an error message is useful, but providing a retry option can improve the user experience.
For example, if a component fails because of temporary data or application conditions, the user may want to try rendering it again.
Example:
import React from "react";
class ErrorBoundary extends React.Component {
state = {
hasError: false
};
static getDerivedStateFromError() {
return {
hasError: true
};
}
componentDidCatch(error, errorInfo) {
console.error(error, errorInfo);
}
resetError = () => {
this.setState({
hasError: false
});
};
render() {
if (this.state.hasError) {
return (
<div>
<h2>Something went wrong.</h2>
<button onClick={this.resetError}>
Try Again
</button>
</div>
);
}
return this.props.children;
}
}
Important: Resetting the Error Boundary only allows the child tree to render again. It does not automatically fix the underlying error. If the same problem still exists, the boundary may catch it again.
For more reliable recovery, reset the boundary when the relevant page, route or data input changes, or use an Error Boundary library that supports reset keys and reset callbacks.
9. Using Error Boundaries with React Router
In applications with multiple routes, it is useful to handle rendering errors at the route level.
React Router provides route error handling through its errorElement option when using a data router.
Example:
import {
createBrowserRouter,
RouterProvider
} from "react-router-dom";
import HomePage from "./HomePage";
import ProductsPage from "./ProductsPage";
import RouteErrorPage from "./RouteErrorPage";
const router = createBrowserRouter([
{
path: "/",
element: <HomePage />,
errorElement: <RouteErrorPage />
},
{
path: "/products",
element: <ProductsPage />,
errorElement: <RouteErrorPage />
}
]);
function App() {
return <RouterProvider router={router} />;
}
export default App;
RouteErrorPage.jsx:
import { useRouteError } from "react-router-dom";
function RouteErrorPage() {
const error = useRouteError();
return (
<div>
<h2>Unable to load this page.</h2>
<p>Please try again later.</p>
</div>
);
}
export default RouteErrorPage;
React Router's route error handling can catch errors from route rendering, loaders and actions. It is not identical to a general-purpose React Error Boundary, so choose the appropriate mechanism for the type of error.
10. What Errors Do Error Boundaries Catch?
Error Boundaries catch errors in their descendant component tree during React rendering and certain React lifecycle operations.
| Error Type | Caught by Error Boundary? |
|---|---|
| Error during component rendering | Yes |
| Error in a descendant lifecycle method | Yes |
| Error in a descendant constructor | Yes, subject to boundary placement |
| Error inside an event handler | No |
| Error inside setTimeout callback | No |
| Error inside Promise rejection | No |
| Error during server-side rendering | No, not through client Error Boundaries |
Important: Error Boundaries do not catch every JavaScript error. Event handlers, asynchronous callbacks and Promise rejections need their own error handling.
11. How to Handle Errors in Event Handlers
Errors inside event handlers are not automatically caught by Error Boundaries.
Use try/catch to handle errors explicitly.
Example:
function SaveButton() {
async function handleSave() {
try {
const response = await fetch("/api/save", {
method: "POST"
});
if (!response.ok) {
throw new Error("Unable to save data");
}
console.log("Data saved successfully");
} catch (error) {
console.error("Save failed:", error);
}
}
return (
<button onClick={handleSave}>
Save
</button>
);
}
Here, try/catch handles the asynchronous operation. The Error Boundary does not automatically catch errors from this event handler.
12. Error Boundaries vs API Error Handling
It is important to understand that API errors and rendering errors are different.
| Feature | Error Boundary | API Error Handling |
|---|---|---|
| Purpose | Handles errors in React component rendering | Handles failed API requests and responses |
| Typical errors | Rendering exceptions | Network failures, HTTP errors |
| Handling mechanism | React Error Boundary | try/catch, query error states |
| Fallback | Fallback component UI | Error message, retry button |
Example:
If the product API returns an HTTP 500 response, handle that failure in the API or data-fetching layer and display an appropriate error message.
If the ProductList component itself throws an exception while rendering the response, an Error Boundary can catch that rendering error.
13. Logging Errors to Monitoring Services
In production applications, logging errors only to the browser console is not sufficient.
We should capture useful information and send it to an appropriate monitoring service.
Examples of monitoring services include:
- Sentry
- Azure Application Insights
- Datadog
- New Relic
Example integration point:
componentDidCatch(error, errorInfo) {
console.error("React error:", error);
// Send the error and component information
// to your configured monitoring service.
}
Useful information to capture includes:
- Error message.
- Component stack.
- Application version.
- Route or page information.
- Relevant non-sensitive diagnostic context.
Security note: Avoid sending passwords, access tokens, payment information or other sensitive user data to error monitoring systems.
14. Common Mistakes to Avoid
- Using only one Error Boundary for everything: Independent sections may need separate boundaries.
- Expecting Error Boundaries to catch API errors automatically: Handle failed requests in the data-fetching layer.
- Expecting Error Boundaries to catch event handler errors: Use try/catch inside event handlers.
- Showing technical error details to users: Display friendly messages instead.
- Not providing recovery options: Consider retry or navigation options where appropriate.
- Ignoring error logging: Capture errors for production debugging.
- Assuming retry always fixes the problem: Resetting a boundary does not repair the underlying error.
- Placing the boundary incorrectly: A boundary cannot catch errors thrown by itself or its fallback UI.
15. Recommended Error Boundary Architecture
For a medium or large React application, use multiple levels of error handling.
Recommended responsibilities:
- Root Error Boundary: Handles unexpected rendering failures across the application.
- Route-level error handling: Displays an appropriate page when route rendering, loaders or actions fail.
- Feature-level Error Boundaries: Protect independent application sections and widgets.
- API error handling: Handles failed network requests and unsuccessful HTTP responses.
- Monitoring: Captures errors for investigation and improvement.
16. Interview Questions and Answers
Q1. What is an Error Boundary in React?
An Error Boundary is a React component that catches errors in its descendant component tree during rendering and displays a fallback UI instead of allowing the affected component tree to fail.
Q2. Which lifecycle methods are used to create Error Boundaries?
getDerivedStateFromError() updates state to display fallback UI, while componentDidCatch() receives error details and can be used for logging.
Q3. Can we create Error Boundaries using functional components?
React does not provide a built-in Hook for creating Error Boundaries. The standard implementation uses a class component. Libraries can provide reusable alternatives with a simpler API.
Q4. Do Error Boundaries catch errors in event handlers?
No. Errors in event handlers should be handled using try/catch or other appropriate error-handling mechanisms.
Q5. Can Error Boundaries catch API errors?
They do not automatically catch asynchronous API failures. API errors should be handled in the API service, try/catch block or data-fetching library.
Q6. Why should we use multiple Error Boundaries?
Multiple boundaries isolate failures. If one independent section fails, other sections can continue working.
Q7. What is the purpose of getDerivedStateFromError()?
It updates the Error Boundary state after a descendant rendering error so that React can display fallback UI.
Q8. What is the purpose of componentDidCatch()?
It receives the error and component stack information. It is commonly used to log errors to monitoring services.
Q9. Can an Error Boundary catch errors inside itself?
No. An Error Boundary cannot catch errors thrown by itself or its fallback UI. An outer Error Boundary may catch those errors.
Q10. How do you implement Error Boundaries in a production application?
Use a root boundary, feature-level boundaries, route-level error handling where appropriate, API error handling, user-friendly fallback interfaces and centralized error monitoring.
17. Final Takeaways
- Error Boundaries protect React component trees from rendering failures.
- Use
getDerivedStateFromError()to display fallback UI. - Use
componentDidCatch()to capture error details. - Place boundaries around independent application sections.
- Use try/catch for event handlers and asynchronous operations.
- Handle API failures separately from rendering failures.
- Provide retry or recovery options where appropriate.
- Use monitoring services to investigate production errors.
Most important principle: Design Error Boundaries to isolate failures. A problem in one feature should not unnecessarily prevent users from accessing other working parts of the application.
| How to Manage State Across Multiple Pages :👈 | 👉:How to Organize a Large React Codebase |
Comments and Discussion