InterviewHubPRO
Section Overview
Q421

Question 421 of 445

Part 11: Legacy Architecture, Migration Patterns & Historical Internals (354 - 445)

95%
React & Modern Frontend (445 Qs)•Part 11: Legacy Architecture, Migration Patterns & Historical Internals (354 - 445)

What are the methods invoked during error handling?

Below methods are called when there is an error during rendering, in a lifecycle method, or in the constructor of any child component.

scss
1.  static getDerivedStateFromError()
2.  componentDidCatch()

Code Example

tsx
import React, { Component, ErrorInfo, ReactNode } from 'react';

interface Props { children: ReactNode; }
interface State { hasError: boolean; errorMessage: string; }

export class ErrorBoundaryHandler extends Component<Props, State> {
  state: State = { hasError: false, errorMessage: '' };

  // 1. static getDerivedStateFromError: Render fallback UI immediately
  static getDerivedStateFromError(error: Error): State {
    return { hasError: true, errorMessage: error.message };
  }

  // 2. componentDidCatch: Log error telemetry to monitoring systems
  componentDidCatch(error: Error, info: ErrorInfo) {
    console.error('Error Boundary caught error:', error, info.componentStack);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="p-4 border border-red-500 bg-red-50 rounded">
          <h2 className="text-red-700 font-bold">Something went wrong</h2>
          <p className="text-red-600 text-sm">{this.state.errorMessage}</p>
        </div>
      );
    }
    return this.props.children;
  }
}