सामग्री पर जाएँ

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

रिज़्यूमे देखें

सामान्य इंजीनियरिंग, हेल्थ-टेक, फ़िनटेक और अधिक के लिए तैयार संस्करण।

  • छह केंद्रित रूप
  • प्रिंट-तैयार PDF
  • हर भूमिका के लिए अपडेट
मेरा रिज़्यूमे पढ़ें
luizepauloxd@gmail.com

ईमेल पसंद है? सीधे लिखें, या यहाँ ड्राफ़्ट शुरू करें।

बताएँ आपके मन में क्या है।

© 2026 Luiz Fernando इरादे से बना। और थोड़ी जिज्ञासा से।ऊपर जाएँ