Building reliable and user-friendly applications is one of the main goals of every React developer. While React provides an efficient and flexible way to create user interfaces, even the best applications can encounter unexpected errors — whether due to a bug in a component, incorrect API response, or a third-party integration issue. Learn Error Boundaries in React to handle runtime errors gracefully, improve app stability, and provide a better user experience in React applications.
Without proper error handling, these issues can crash entire sections of your app, creating a frustrating user experience. To address this, React introduced Error Boundaries — a powerful feature that allows developers to handle runtime errors gracefully in React components.
What Are Error Boundaries?
Error Boundaries are React components that catch JavaScript errors anywhere in their child component tree and display a fallback UI instead of crashing the entire app.
In simple terms, think of them as try-catch blocks for React components. While JavaScript’s try-catch works for imperative code, Error Boundaries are the declarative way to handle errors in React’s component tree.
When an error occurs during rendering, in lifecycle methods, or in constructors of child components, an Error Boundary can catch that error and display an alternative UI — often a simple “Something went wrong” message — while keeping the rest of the application running smoothly.
When and Where Error Boundaries Work
Error Boundaries can catch errors in the following cases:
- • During the rendering of components.
- • Inside lifecycle methods (like componentDidMount, componentDidUpdate).
- • Within the constructors of class components.
However, they do not catch errors in the following cases:
- • Inside event handlers (you must use try-catch manually here).
- • Asynchronous code, such as callbacks, setTimeout, or Promises.
- • Server-side rendering (SSR).
- • Errors thrown inside the error boundary itself.
Why Do We Need Error Boundaries?
React applications can become complex very quickly. A small bug in one component can potentially crash the entire app if not handled correctly.
Let’s consider a scenario — you have a dashboard where multiple widgets render data from different APIs. If one widget crashes due to a bad API response, it should not break the entire dashboard. Instead, you can wrap each widget with an Error Boundary so that only the faulty one shows an error message while others continue working.
This leads to:
- • Improved user experience – the app doesn’t crash entirely.
- • Better debugging – developers get clear insights into which part failed.
- • Graceful recovery – users can retry, reload, or continue using other sections.
Creating an Error Boundary
Error Boundaries can only be created using class components.
Example: Basic Error Boundary
import React from "react";
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update state to display fallback UI
return { hasError: true };
}
componentDidCatch(error, info) {
// Log error details for debugging
console.error("Error caught by Error Boundary:", error, info);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h2>Something went wrong. Please try again later.</h2>;
}
return this.props.children;
}
}
export default ErrorBoundary;
Using the Error Boundary
import ErrorBoundary from "./ErrorBoundary";
import MyWidget from "./MyWidget";
function Dashboard() {
return (
<div>
<ErrorBoundary>
<MyWidget />
</ErrorBoundary>
</div>
);
}
Now, if MyWidget throws an error while rendering, React will catch it and display the fallback message instead of crashing the entire dashboard.
Source: URL 1 – React JS Error Boundaries
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.
Example: Error Boundary in Action
import React from "react";
class BuggyCounter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
handleClick = () => {
this.setState(({ count }) => ({ count: count + 1 }));
};
render() {
if (this.state.count === 5) {
throw new Error("Counter crashed!");
}
return <h3 onClick={this.handleClick}>{this.state.count}</h3>;
}
}
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, info) {
console.log("Error:", error, info);
}
render() {
if (this.state.hasError) {
return <h2>Something went wrong with the counter.</h2>;
}
return this.props.children;
}
}
export default function App() {
return (
<div>
<ErrorBoundary>
<BuggyCounter />
</ErrorBoundary>
<ErrorBoundary>
<BuggyCounter />
</ErrorBoundary>
</div>
);
}
In this example, clicking on a counter increases its value. When the count reaches 5, it deliberately throws an error. Because each counter is wrapped in its own Error Boundary, only the faulty counter displays the fallback message, while the other continues working normally.
Handling Errors in Functional Components
React doesn’t yet provide hooks-based APIs for creating error boundaries directly in functional components. However, you can still use Error Boundary components to wrap functional components.
Alternatively, libraries like react-error-boundary by Kent C. Dodds offer a simpler way to implement this in functional components using hooks and render props.
Example using react-error-boundary:
import { ErrorBoundary } from "react-error-boundary";
function FallbackComponent({ error, resetErrorBoundary }) {
return (
<div>
<p>Something went wrong: {error.message}</p>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
function BuggyComponent() {
throw new Error("Oops!");
}
export default function App() {
return (
<ErrorBoundary
FallbackComponent={FallbackComponent}
onReset={() => console.log("Reset!")}
>
<BuggyComponent />
</ErrorBoundary>
);
}
This modern approach provides a clean way to manage errors while keeping components functional.
Best Practices for Using Error Boundaries
Here are some practical tips to get the most out of Error Boundaries:
1. Wrap critical UI sections – Use Error Boundaries around key components like dashboards, widgets, or routes.
2. Provide user-friendly fallback UI – Instead of generic text, show meaningful recovery options (e.g., “Reload page” or “Go back”).
3. Log errors – Use services like Sentry or LogRocket to record caught errors for debugging.
4. Keep boundaries small and focused – Avoid wrapping the entire app with a single boundary; use multiple small ones for modular handling.
5. Use for production safety – Don’t rely on them for debugging; use them to prevent app crashes in production environments.
Error Boundaries are a crucial part of building resilient React applications. They ensure that a single broken component doesn’t compromise the entire user interface.
By catching rendering errors and displaying fallback UIs, Error Boundaries help maintain a seamless experience, allowing users to continue interacting with unaffected parts of your app.
Source: URL 1 – React JS Error Boundaries
Error Boundaries should be plain and exclusively concerned with error handling — not business logic.
Source: URL 2 – Error Boundaries in React Explained
Instead of a boring message, give users a better experience:
if (this.state.hasError) {
return (
<div>
<h1>Oops! Something broke </h1>
<p>Please refresh or try again later.</p>
</div>
);
}
Yes! You can allow users to retry:
<button onClick={() => this.setState({ hasError: false })}>
Try Again
</button>
This allows users to retry after an error occurs.
Source: URL 1 – React JS Error Boundaries
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.
Source: URL 2 – Error Boundaries in React Explained
Error Boundary vs Try-Catch
Feature
Error Boundary
Try-Catch
UI Errors
Yes
No
Event Errors
No
Yes
Async Code
No
Yes
In short:
Error Boundaries don’t prevent bugs, but they make your app more resilient when bugs appear.
Source: URL 1 – React JS Error Boundaries
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.
Source: URL 2 – Error Boundaries in React Explained
Frequently Asked Questions (FAQs):
1. Error Boundaries in React: What are they?
Error Boundaries are components defined in React that catch JavaScript errors across their child components, log those errors, and display a fallback UI when such an error happens instead of crashing the entire app.
2. What is an Error Boundary in React, and how to create it?
You implement it as a class component with lifecycle methods such as componentDidCatch or getDerivedStateFromError.
3. Which errors are caught by Error Boundaries?
They log caught during rendering and lifecycle methods, as well as in constructors of child components.
4. What are errors that Error Boundaries DO NOT catch?
They do not catch errors in event handlers, asynchronous code, or server-side rendering. Or errors that are thrown from within them.
5. Error Boundaries in React apps — why to use it?
They enhance UX by not crashing the whole app and displaying fallback UI when errors occur.
Do visit our channel to explore more: SevenMentor
Author :- Sarika kore
Sarika kore
Expert trainer and consultant at SevenMentor with years of industry experience. Passionate about sharing knowledge and empowering the next generation of tech leaders.