Error Boundaries are special class-based React components designed to catch runtime errors that occur during rendering, lifecycle methods, and constructors of their child components.
Instead of allowing the entire application UI to crash, Error Boundaries display a fallback UI and keep the rest of the application running smoothly.
getDerivedStateFromError updates internal state when an error occurscomponentDidCatch receives error details and stack information
// Error Boundary implemented using a class component
import React from "react";
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Trigger fallback UI on error
return { hasError: true };
}
componentDidCatch(error, info) {
// Capture error details for logging or monitoring
console.error("Caught by ErrorBoundary:", error, info);
}
render() {
if (this.state.hasError) {
return <h3>Something went wrong.</h3>;
}
return this.props.children;
}
}
export default ErrorBoundary;
// Component that crashes intentionally
function BuggyComponent() {
throw new Error("Component crashed!");
}
// Wrapping the buggy component with ErrorBoundary
<ErrorBoundary>
<BuggyComponent />
</ErrorBoundary>
When BuggyComponent throws an error, React stops rendering that component tree. The Error Boundary intercepts the error, updates its internal state, and displays a fallback message instead of breaking the entire UI.
All other components outside the Error Boundary continue to work normally.
componentDidCatchGoal: Understand how Error Boundaries protect React apps from runtime crashes.