React Error Boundaries β Catch JavaScript Errors in Components (2025 Guide)
Introduction β Why Use Error Boundaries?
In React.js, JavaScript errors in a component tree can break the entire UI, leading to blank screens and frustrated users. React Error Boundaries are the solution.
An Error Boundary is a special component that catches JavaScript errors anywhere in its child component tree, logs them, and displays a fallback UI without crashing the whole app.
In this guide, youβll learn:
- What Error Boundaries are and how they work
- How to create and implement one
- Best practices and common use cases
- Limitations and how they compare to try/catch
1. What Are Error Boundaries?
Error Boundaries are React class components that implement lifecycle methods to catch rendering errors and provide fallback UIs.
They catch errors during:
- Rendering
- Lifecycle methods
- Constructors of child components
They do NOT catch:
- Asynchronous code (
setTimeout,fetch) - Event handlers
- Server-side rendering errors
2. Create a Basic Error Boundary
import React from 'react';
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, errorInfo) {
console.error('Error caught:', error, errorInfo);
// Optionally log to external services like Sentry
}
render() {
if (this.state.hasError) {
return <h2>Something went wrong π’</h2>;
}
return this.props.children;
}
}
export default ErrorBoundary;
Usage:
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>
Catches any error thrown inside <MyComponent>
Displays fallback UI without breaking the app
3. Error Boundary with Custom Fallback UI
function FallbackUI({ error, reset }) {
return (
<div className="error">
<h2>Oops! {error.message}</h2>
<button onClick={reset}>Try Again</button>
</div>
);
}
Modify Error Boundary:
render() {
if (this.state.hasError) {
return this.props.fallback || <FallbackUI error={this.state.error} />;
}
return this.props.children;
}
Flexible fallback rendering
Support for reset and recovery
4. Best Places to Use Error Boundaries
| Use Case | Reason |
|---|---|
| Component galleries | Prevent 1 failed widget from crashing all others |
| Content blocks | Show fallback for broken sections only |
| Route wrappers | Catch per-page crashes (404s, SSR errors) |
| Auth areas | Guard against runtime errors on login/logout flows |
5. Error Boundaries vs try/catch
| Feature | Error Boundary | try/catch block |
|---|---|---|
| Scope | Renders + lifecycle | Synchronous JS only |
| Works in UI render | Yes | No (throws error) |
| Asynchronous errors | No | Yes (with async/await) |
| Used for | Visual fallback | Control flow |
Use try/catch for async logic; use error boundaries for UI rendering errors
6. Tools That Use Error Boundaries
- React DevTools: Help detect and isolate boundary breaks
- Sentry, LogRocket, Datadog: Capture errors via
componentDidCatch - Next.js: Supports per-page error boundaries for SSR/SPA fallback
- React Router: Supports boundaries via
<ErrorBoundary>in route config
Best Practices
Create a global error boundary at the App level
Use multiple boundaries for isolated features (modals, widgets, routes)
Always log errors in componentDidCatch()
Provide meaningful fallback UIs to enhance UX
Reset boundary state on retries or route changes
Summary β Recap & Next Steps
React Error Boundaries are vital for resilient user interfaces. They prevent a single component crash from breaking the entire app and improve debugging, logging, and user experience.
Key Takeaways:
- Use class components to create Error Boundaries
- Wrap unstable or remote-rendered components with boundaries
- Catch render and lifecycle errorsβnot async/event errors
- Pair with fallback UI and error tracking tools
- Use multiple boundaries for scoped recovery
Real-World Relevance:
Used in production apps like Facebook, Jira, and Slack to catch UI failures gracefully and keep the interface running.
FAQ Section
Can I use Error Boundaries in functional components?
Not directly. Error Boundaries must be class components, but you can wrap them around functional components.
Do Error Boundaries catch async errors in fetch()?
No. Use try/catch inside async functions to handle those.
Can I use multiple Error Boundaries?
Yes. Itβs recommended to use multiple smaller boundaries to isolate failure.
Are Error Boundaries available in React 18?
Yes. Theyβre stable since React 16 and work in all React versions β₯16.
Should I log errors in componentDidCatch()?
Absolutely. Log them to services like Sentry, Datadog, or your custom logger.
Share Now :
