CodeBlanks Logo Icon CodeBlanks

Summary - Error boundary

Write a boundary that wraps a widget and shows a fallback on error.

Summary - Error boundary

In this group you learned what an error boundary is, its class component structure, and fallback UI design. The boundary catches errors in its subtree and switches to a fallback.

Three key parts: getDerivedStateFromError updates state, componentDidCatch logs, render draws fallback or children. In the last step you combine all parts.

Practice Full error boundary

Complete the skeleton below. Write an ErrorBoundary class; include getDerivedStateFromError, componentDidCatch methods and a render that returns <h1>Error</h1> if hasError is true. 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 componentDidCatch do?

  • Cancels rendering
  • Yan etki yapar Correct answer
  • Render eder
  • Updates state

Explanation: componentDidCatch performs side effects, like logging.

2 Summary match

Term Meaning
getDerivedStateFromError Updates state
componentDidCatch Logs
hasError Error state
fallback UI Friendly message

All lessons in Intermediate