In building real-world React applications, error handling is as important as building features. But no matter how well you write your code, things can go wrong — an API fails to respond (it’s down), a rendering bug happens, or a component crashes due to bad data. This is where Error Boundaries help us.
In this article, you will learn how to use an error boundary in your React application so that only the part of the interface that failed renders correctly and protects the rest. Rather than rendering a blank screen or crashing the app entirely, you can include a fallback UI and even log the error for debugging purposes.
What Are Error Boundaries?
Error Boundaries are specific React components that handle JavaScript errors in their child component tree, during render, in lifecycle methods, and constructors. They allow you to catch an error and render a fallback UI instead of crashing the entire application.
In other words, they are used as a safety net for your UI.
Why Do We Need Error Boundaries?
Without Error Boundaries, if a React component throws an error, the whole app would crash. Due to this, especially in production, it mostly caused a bad user experience.
With Error Boundaries:
- You can confine issues to certain parts of the UI.
- The rest of your app works just as it always does.
- Instead of a broken screen, users see a meaningful message.
- Developers can log errors to debug and track.
So, for instance, if a dashboard has multiple widgets and one of those fails, Error Boundaries will only fail that single widget — not the entire dashboard.
How Error Boundaries Work
Error Boundaries is written using class components. React provides two error boundary lifecycle methods:
static getDerivedStateFromError(error)
componentDidCatch(error, info)
getDerivedStateFromError
This will be called to set the state on an error. Usually, you toggle a flag to display some fallback UI.
componentDidCatch
This is the method used to log errors. Optionally, you can log error details to a logging service or console.
Creating an Error Boundary
So let’s define a simple Error Boundary component:
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, info) {
console.error("Error caught:", error, info);
}
render() {
if (this.state.hasError) {
return <h2>Something went wrong. Please try again.</h2>;
}
return this.props.children;
}
}
export default ErrorBoundary;
Explore Other Demanding Courses
No courses available for the selected domain.
Using an Error Boundary
Once you’ve created an Error Boundary, you can wrap it around any component:
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>
You can also wrap specific sections instead of the entire app:
<ErrorBoundary>
<Header />
</ErrorBoundary>
<ErrorBoundary>
<MainContent />
</ErrorBoundary>
That way, if MainContent goes down, Header still works.
Best Practices for Error Boundaries
1. Use Multiple Error Boundaries
Correct – Multiple boundaries per sections instead of wrapping the whole app with a single Error Boundary. This ensures better fault isolation.
2. Show Meaningful Fallback UI
Do not send generic messages such as “Something went wrong. Instead, guide the user:
Offer a retry button
Provide navigation options
Suggest refreshing the page
3. Log Errors Properly
componentDidCatch allows you to log errors to external services, like Sentry or your own backend. This facilitates the quick identification and resolution of issues.
4. Keep It Lightweight
Error Boundaries should be plain and exclusively concerned with error handling — not business logic.
What Error Boundaries DO NOT Catch
Understanding their limitations is important. Error Boundaries do not catch errors in the following:
- Event handlers (like onClick)
- Asynchronous code (e.g., setTimeout, promises)
- Server-side rendering
- Mistakes raised within the Error Bound itself
You will have to use the traditional try for these cases...catch statements or other error handling methods.
Functional Components and Error Boundaries
Error Boundaries currently must be class components. But, Error Boundaries still can be used in the case of Functional Components by wrapping them.
Libraries such as react-error-boundary also exist by third-party devs to help use Error Boundaries in functional components.
Real-World Example
To understand the concept, imagine an e-commerce app with a product list component that relies on some API. A certain scenario will crash the component if API doesn't work or it returns some data which wasn't expected.
Without Error Boundaries:
The entire app crashes
User sees blank screen
With Error Boundaries:
The error message is only displayed in the product list section
Navbar, footer, and cart — the rest of the app instance work
This small adjustment provides a better user experience!
When to Use Error Boundaries?
You should use Error Boundaries in the following scenarios:
- Applications with a large number of UI sections
- Items that depend on an external point of information
- Key UI sections such as dashboards, payments, or forms
Conclusion
Error Boundaries are a must-know concept while building a resilient React app. They allow you to handle unexpected errors gracefully, enhance the user experience, and simplify debugging.
They do not replace all forms of error handling, but they allow you to protect your UI from becoming completely broken. Employing them strategically can allow you to create applications that work but are also robust.
Have you noticed how, as your applications are becoming more complex, Error Boundaries become less an option than a necessity?
Related Links:
Advantages and Disadvantages of AI
Do visit our channel to know more: SevenMentor
Author:-
Pritesh Dhanad
Pritesh Dhanad
Expert trainer and consultant at SevenMentor with years of industry experience. Passionate about sharing knowledge and empowering the next generation of tech leaders.
Call the Trainer and Book your free demo Class..... Call now!!!
| SevenMentor Pvt Ltd.
© Copyright 2025 | SevenMentor Pvt Ltd.
