Beginner LevelReact JS & React 19
What is an Error Boundary in React and why must it be written as a Class Component?
❓ Interview Prompt: Explain Error Boundaries, catching render errors, `componentDidCatch`, `getDerivedStateFromError`, and fallback UIs.
An Error Boundary is a component that catches JavaScript errors anywhere in its child component tree, logs the errors, and displays a fallback UI instead of crashing the entire application.
Why Class Components?
Error Boundaries MUST be class components because there are no React hooks equivalent to the class lifecycle methods 'static getDerivedStateFromError()' and 'componentDidCatch()'!
Code Implementation Example
jsx
import React from 'react';
class ErrorBoundary extends React.Component {
state = { hasError: false, error: null };
static getDerivedStateFromError(error) {
// Update state so next render shows fallback UI
return { hasError: true, error };
}
componentDidCatch(error, errorInfo) {
// Log error to telemetry service (Sentry, Datadog)
logErrorToService(error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h2>Something went wrong. Please refresh.</h2>;
}
return this.props.children;
}
}💡Implementing a class-based Error Boundary with fallback UI.
🎯 Interview Key Takeaway
Error Boundaries catch rendering errors in child component trees, preventing full application crash screens.
#Error Boundary#Class Component#Error Handling#Beginner
Back to all React JS & React 19 Questions→