CodeBlanks Logo Icon CodeBlanks

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.

Practice 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.

Starter code

App.jsx
import { Component } from "react";

// Write the ErrorBoundary class here

Sample solution

App.jsx
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;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does getDerivedStateFromError return?

  • Bir dizi
  • Bir dize
  • Bir state nesnesi Correct answer
  • A number

Explanation: getDerivedStateFromError returns a state object.

2 Initial state

Question
class ErrorBoundary extends Component {
  state = { hasError: ____ };
}
Answer
class ErrorBoundary extends Component {
  state = { hasError: false };
}

Explanation: hasError starts as false; becomes true on error.

3 Class component structure: match the terms

Term Meaning
getDerivedStateFromError Updates state
componentDidCatch Runs side effects
hasError Error state
render Decides the render

All lessons in Intermediate