Error Boundaries in React are components designed to catch JavaScript errors that occur in their child component tree, preventing the entire app from crashing.
They allow you to gracefully handle errors — for example, by showing a fallback UI instead of a blank screen or broken app.
🧠 What Error Boundaries Do
They catch:
- Runtime errors in rendering
- Lifecycle methods (like
componentDidMount) - Constructors of child components
They don’t catch:
- Errors inside event handlers
- Errors in asynchronous code (like
setTimeoutor promises) - Errors in server-side rendering
⚙️ Error Boundaries in Class Components
Error boundaries were introduced in React 16, and you create one by defining a class component that implements two special lifecycle methods:
static getDerivedStateFromError(error)→ to update state and show a fallback UI.componentDidCatch(error, info)→ to log or report the error.
🧩 Example:
import React from "react";
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update state to show fallback UI
return { hasError: true };
}
componentDidCatch(error, info) {
// Log error details
console.error("Error caught by boundary:", error, info);
}
render() {
if (this.state.hasError) {
return <h2>Something went wrong.</h2>;
}
return this.props.children;
}
}
export default ErrorBoundary;
✅ Usage:
<ErrorBoundary>
<ProblematicComponent />
</ErrorBoundary>
If ProblematicComponent throws an error, the boundary catches it and displays the fallback message.
⚛️ Error Handling in Functional Components
Functional components cannot be true error boundaries (because they don’t have lifecycle methods).
However, there are workarounds using hooks or third-party helpers.
🧩 Option 1: Using react-error-boundary package
npm install react-error-boundary
Example:
import { ErrorBoundary } from "react-error-boundary";
function Fallback({ 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={Fallback}
onReset={() => window.location.reload()}
>
<BuggyComponent />
</ErrorBoundary>
);
}
✅ This provides functional-style error handling equivalent to class-based error boundaries.
🧱 Summary
| Feature | Class Component | Functional Component |
|---|---|---|
| Built-in lifecycle methods | ✅ (getDerivedStateFromError, componentDidCatch) |
❌ Not available |
| Can act as true error boundary | ✅ | ❌ |
| Workaround | — | Use react-error-boundary or custom try/catch logic |
| Use case | Catch rendering/runtime errors in children | Same, but via library |
In short:
Error Boundaries keep your React app from crashing due to runtime errors by showing a fallback UI — and they’re built with class components (or external helpers for functional ones).