What You'll Learn
You'll learn how static getDerivedStateFromError updates your error boundary's state during the render phase, letting you display fallback UI safely without side effects.
The Render-Phase State Update Method
While componentDidCatch handles logging and side effects after an error, static getDerivedStateFromError runs during the render phase to immediately update state. This is React's mechanism for switching from your broken component tree to a fallback UI.
How It Works
This static method receives the error that was thrown and returns a new state object. React uses this returned state to re-render your error boundary with the fallback UI:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update state so next render shows fallback
return { hasError: true };
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
Why It's Static and Pure
The method is static (no access to this) and must be pure (no side effects) because it runs during rendering. Think of it like getDerivedStateFromProps but triggered by errors instead of props. You can't log errors here, make API calls, or update refs—that's what componentDidCatch is for.
You can examine the error to return different state:
static getDerivedStateFromError(error) {
return {
hasError: true,
errorType: error.name === 'NetworkError' ? 'network' : 'general'
};
}
The Typical Pattern
Most error boundaries use getDerivedStateFromError for state updates and componentDidCatch for logging—they work together as a team.
Key Takeaway: static getDerivedStateFromError is a pure, static method that returns new state during rendering to enable fallback UI, while keeping side effects out of the render phase.