React Mastery / Advanced Concepts

Error Boundary

🐞 Error Handling in React Component (When something goes wrong)

Sometimes components break. React helps you catch and handle errors gracefully instead of crashing the whole app.

Sometimes, a component throws an error (bug, undefined value, crash).

Without handling, this can break the entire app.

👉 Error Boundaries allow React to:

  • Catch errors safely

  • Show a fallback UI

  • Prevent the whole app from crashing

Lifecycle methods used:

Method

What it does

getDerivedStateFromError()

Updates the state to show a fallback UI.

componentDidCatch()

Catches errors and logs them or reports them.


❓ What is an Error Boundary?

An Error Boundary is a class component that:

  • Catches JavaScript errors in child components

  • Displays a fallback UI

  • Logs or reports the error

⚠️ Error Boundaries must be class components

(Hooks do NOT support error boundaries yet)

✅ Example of an Error Boundary:

import React from "react";

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  // 1️⃣ Update state when error happens
  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  // 2️⃣ Catch error details
  componentDidCatch(error, info) {
    console.error("Error caught:", error);
    console.error("Component stack:", info.componentStack);
  }

  render() {
    if (this.state.hasError) {
      return <h2>⚠️ Something went wrong.</h2>;
    }

    return this.props.children;
  }
}

export default ErrorBoundary;

How to Use an Error Boundary

<ErrorBoundary>
	<BuggyComponent />
</ErrorBoundary>

If BuggyComponent crashes:

  • Only that part shows fallback UI

  • Rest of the app works fine

💥 What Errors Are Caught?

  • Errors in render()

  • Errors in lifecycle methods

  • Errors in constructors of child components

❌ What Errors Are NOT Caught?

  • Event handlers (onClick, onChange)

  • Async code (setTimeout, fetch)

  • Errors inside the error boundary itself

  • These must be handled with try/catch

🟪 Complete Error Boundary Example (Real Usage)

We’ll create:

  1. A Buggy component (throws an error)

  2. An ErrorBoundary

  3. An App that uses it


✅ Full WORKING Example

import React from "react";

class BuggyCounter extends React.Component {
  state = { count: 0 };

  handleClick = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    // 💥 Crash when count reaches 5
    if (this.state.count === 5) {
      throw new Error("Counter crashed at 5!");
    }

    return (
      <div>
        <h3>Count: {this.state.count}</h3>
        <button onClick={this.handleClick}>Increase</button>
      </div>
    );
  }
}

export default BuggyCounter;
import React from "react";

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  // 1️⃣ Update UI when error happens
  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  // 2️⃣ Log error details
  componentDidCatch(error, info) {
    console.error("Error:", error);
    console.error("Stack:", info.componentStack);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div style={{ color: "red" }}>
          <h2>Something went wrong.</h2>
          <p>Please refresh the page.</p>
        </div>
      );
    }

    return this.props.children;
  }
}

export default ErrorBoundary;
import React from "react";
import ErrorBoundary from "./ErrorBoundary";
import BuggyCounter from "./BuggyCounter";

function App() {
  return (
    <div>
      <h1>Error Boundary Demo</h1>

      <ErrorBoundary>
        <BuggyCounter />
      </ErrorBoundary>
    </div>
  );
}

export default App;


🔄 What Happens at Runtime?

  1. App loads → everything works normally

  2. Click Increase button

  3. Count reaches 5

  4. Buggy component throws error

  5. ErrorBoundary catches it

  6. Fallback UI is shown

  7. App does NOT crash


❌ Without Error Boundary

  • App crashes completely

  • White screen

  • Poor user experience

✔ With Error Boundary

  • Only broken component is replaced

  • App remains stable

  • Error is logged for debugging