Required Lifecycle Method
componentDidCatch(error, info)
This method catches errors from child components during:
- rendering
- lifecycle methods
- constructors
Example:
componentDidCatch(error, info) {
console.log("Error:", error);
console.log("Info:", info);
}
⭐ Recommended (Optional) Lifecycle Method
static getDerivedStateFromError(error)
This updates UI when there’s an error (e.g., show fallback UI).
static getDerivedStateFromError(error) {
return { hasError: true };
}
🧱 Minimal Error Boundary Example
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, info) {
console.log("Logged Error:", error, info);
}
render() {
if (this.state.hasError) return <h2>Something went wrong.</h2>;
return this.props.children;
}
}
🎯 Short Interview Answer
The required lifecycle method for an Error Boundary is
componentDidCatch(), which captures errors from child components.
Often,static getDerivedStateFromError()is also used to show fallback UI.