本文へスキップ

Understanding ErrorBoundary in React: A Comprehensive Guide

Understanding ErrorBoundary in React: A Comprehensive Guide

Hello my name is Luiz and in this Article we are going to cover how Error Boundaries work in React

Error Boundaries are a powerful feature in React that allow you to catch JavaScript errors anywhere in your component tree, log those errors, and display a fallback UI instead of crashing the entire application. Let's dive into how they work by examining a practical implementation.

What Are Error Boundaries?

Error Boundaries are React components that catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them. They act as a safety net for your application, preventing a single component failure from breaking your entire UI.

The Implementation

Here's the ErrorCatcher component that demonstrates this pattern:

import { ErrorInfo, PureComponent, ReactNode } from "react";

type ErrorBoundaryState = {
  hasError: boolean;
};

type ErrorBoundaryProps = {
  onBoundaryError: (error: Error, errorInfo: ErrorInfo) => void;
  fallback: ReactNode;
};

class ErrorCatcher extends PureComponent<
  ErrorBoundaryProps,
  ErrorBoundaryState
> {
  constructor(props: ErrorBoundaryProps) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error: Error) {
    return { hasError: true, error };
  }

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    this.props.onBoundaryError?.(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      if (!this.props.fallback) {
        return null;
      }
      return this.props.fallback;
    }
    return this.props.children;
  }
}

function ExampleError(): JSX.Element {
  throw new Error("Example error");
}

function Root() {
  return (
    <ErrorCatcher
      fallback={<div>Something went wrong!</div>}
      onBoundaryError={(error, errorInfo) => {
        console.error("Error caught:", error, errorInfo);
        // Send to error tracking service
      }}
    >
      <ExampleError />
    </ErrorCatcher>
  );
}

Breaking Down the Code

State Initialization constructor

The component maintains a simple state to track whether an error has occurred:

this.state = { hasError: false };

This boolean flag determines whether to render the normal content or the fallback UI.

getDerivedStateFromError

This static lifecycle method is called when a descendant component throws an error:

static getDerivedStateFromError(error: Error) {
  return { hasError: true, error };
}

Key characteristics:

  • Called during the render phase
  • Must be a pure function
  • Updates state to trigger a re-render with fallback UI
  • Receives the error as a parameter

componentDidCatch

This method is called after an error has been thrown:

componentDidCatch(error: Error, errorInfo: ErrorInfo) {
  this.props.onBoundaryError?.(error, errorInfo);
}

Purpose:

  • Called during the commit phase
  • Allows side effects like error logging
  • Receives both the error and additional error information
  • Perfect for sending error reports to monitoring services

Render Logic

The render method implements the fallback behavior:

render() {
  if (this.state.hasError) {
    if (!this.props.fallback) {
      return null;
    }
    return this.props.fallback;
  }
  return this.props.children;
}

Flow:

  1. If an error occurred, check for a fallback component
  2. If no fallback is provided, render nothing (null)
  3. If a fallback exists, render it
  4. Otherwise, render the children normally

Usage Example

<ErrorCatcher
  fallback={<div>Something went wrong!</div>}
  onBoundaryError={(error, errorInfo) => {
    console.error("Error caught:", error, errorInfo);
    // Send to error tracking service
  }}
>
  <YourComponent />
</ErrorCatcher>

What Error Boundaries Don't Catch

It's important to note that Error Boundaries do not catch errors in:

  • Event handlers (use try-catch instead)
  • Asynchronous code (setTimeout, promises)
  • Server-side rendering
  • Errors thrown in the Error Boundary itself

Best Practices

Strategic Placement: Place Error Boundaries at key points in your component tree. You might have one at the top level and others around specific features.

Meaningful Fallbacks: Provide user-friendly error messages that explain what went wrong and what users can do next.

Error Logging: Always implement the onBoundaryError callback to track errors in production.

Granular Boundaries: Don't wrap everything in a single Error Boundary. Use multiple boundaries to isolate failures and keep unaffected parts of your UI functional.

Development vs Production: Show detailed error information in development but user-friendly messages in production.

Advantages of This Implementation

Flexibility: The optional fallback prop allows different fallback UIs for different contexts.

Extensibility: The onBoundaryError callback enables custom error handling logic.

Performance: Extends PureComponent for optimized re-renders.

Type Safety: Uses TypeScript for compile-time type checking.

Conclusion

Error Boundaries are an essential tool for building resilient React applications. The ErrorCatcher implementation shown here provides a clean, reusable way to handle errors gracefully, improving user experience and making debugging easier. By catching errors at the component level, you can prevent entire application crashes and maintain a smooth user experience even when things go wrong.

Profile picture
Luiz Fernando - シニアソフトウェアエンジニア

読んでくれてありがとう!

この記事を楽しんで読んでいただければ幸いです。ご質問やご意見がございましたら、下記のソーシャル メディアからお気軽にご連絡ください。良い一日をお過ごしください。

Carousel imageCarousel imageCarousel imageCarousel imageCarousel image
次へ / 良い会話から始めましょう

大きなアイデア。
Little Luiz.

実現したいプロダクト、強くしたいチーム。一緒に何ができるか、話してみませんか。

道を選ぶ
01Freelance / Products

プロジェクトの相談

フリーランスでの協業、プロダクト開発、技術的な課題。

  • プロダクトの発見からリリースまで
  • ウェブ、モバイル、バックエンド開発
  • 明確なスコープと直接の協業
一緒につくりましょう
02Hiring / Teams

チームへの採用

エンジニアの採用と長期的な機会。

  • シニアフルスタックエンジニアリング
  • プロダクトの視点と技術的な責任
  • 分散チームでの経験
チームへの採用相談
03Résumé / Versions

履歴書を見る

汎用エンジニアリング、ヘルステック、フィンテックなど、用途別のバージョン。

  • 6つの特化バージョン
  • 印刷用PDFエクスポート
  • 役割ごとに更新
履歴書を見る
luizepauloxd@gmail.com

メールをご希望ですか?直接送るか、こちらで下書きを作成できます。

考えていることを教えてください。

© 2026 Luiz Fernando 意図と、少しの好奇心を込めて。ページの先頭へ