Skip to main content
InterviewHubPRO
Section Overview
Q384

Question 384 of 407

Part 9: React Hooks Deep Dive (262 - 316)

94%
React Core & Hooks (407 Qs)•Part 9: React Hooks Deep Dive (262 - 316)

What are the methods invoked during error handling?

junior LevelCode ExampleHooks

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;
  }
}