componentDidCatch and getDerivedStateFromError
What you'll learn: How class components can catch JavaScript errors in their child component tree and display fallback UI instead of crashing your entire app.
The Problem They Solve
When a component throws an error during rendering, React's default behavior is to unmount the entire component tree — your whole app crashes with a white screen. Error boundaries are special class components that catch these errors and let you gracefully recover.
The Two Error Boundary Methods
getDerivedStateFromError(error) is a static lifecycle method that runs during the render phase. It receives the error and returns a state update to trigger fallback UI:
static getDerivedStateFromError(error) {
// Update state to show fallback UI
return { hasError: true };
}
This is like shouldComponentUpdate — it returns a state change but doesn't cause side effects.
componentDidCatch(error, errorInfo) runs during the commit phase (after the DOM updates). Use it for side effects like error logging:
componentDidCatch(error, errorInfo) {
// Log error to an external service
console.error('Error caught:', error, errorInfo);
}
A Complete Error Boundary
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.error('Error:', error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
Wrap any components that might error:
<ErrorBoundary>
<ProblematicComponent />
</ErrorBoundary>
Key Takeaway: Error boundaries use getDerivedStateFromError to update state for fallback UI and componentDidCatch to log errors, preventing child component crashes from taking down your entire app.