π 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 :
