React
Class component structure
Learn to use getDerivedStateFromError and componentDidCatch.
Class component structure
The error boundary skeleton has three parts: state (hasError), getDerivedStateFromError and render. State holds the error flag, the method catches errors, render decides what to draw.
State starts as false. When an error is thrown, getDerivedStateFromError returns true; React updates state and render runs again.
componentDidCatch runs after the error; it is used for logging or reporting to analytics tools.
componentDidCatch
The componentDidCatch(error, info) method runs after an error is caught. It takes two parameters: the error object and the component stack info. It is suited for side effects.
Common uses: send the error to a monitoring service, show a message to the user, or log it. This method does not update state; getDerivedStateFromError does.
Using both methods together is common: one for state, one for logging. React enforces this separation for performance.
Exercise Add componentDidCatch
Complete the skeleton below. Write an ErrorBoundary class; include getDerivedStateFromError(error) and componentDidCatch(error, info) methods, with render returning <h1>Error</h1> if hasError is true, otherwise this.props.children. Export it.
Show example solution
import { Component } from "react";
class ErrorBoundary extends Component {
state = { hasError: false };
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
console.log(error, info);
}
render() {
if (this.state.hasError) return <h1>Error</h1>;
return this.props.children;
}
}
export default ErrorBoundary;
Test yourself
-
What does getDerivedStateFromError return?
- Bir dizi
- Bir dize
- Bir state nesnesi
- A number
Show answer
Bir state nesnesi — getDerivedStateFromError returns a state object.
-
Initial state
class ErrorBoundary extends Component {
state = { hasError: ____ };
}
Show answer
class ErrorBoundary extends Component {
state = { hasError: false };
}
-
Class component structure: match the terms
- getDerivedStateFromError
- Updates state
- componentDidCatch
- Runs side effects
- hasError
- Error state
- render
- Decides the render
Next lesson: Fallback UI