React › Class Components & Legacy Lifecycle Methods
Why can only class components be used as error boundaries in React?
IntermediateAnswer
Error boundaries need two special lifecycle methods, getDerivedStateFromError and componentDidCatch, which are only available on class components. There is currently no hook version of these methods, so even in a codebase built entirely with function components, error boundaries still need to be written as a small class component.
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
render() {
if (this.state.hasError) return <h1>Something went wrong</h1>;
return this.props.children;
}
}Real-world example A modern app built entirely with function components still includes one small ErrorBoundary class component, used purely to catch and display a friendly message if any part of the app crashes unexpectedly.