REACT Error Boundaries

Error Boundaries are React components that catch JavaScript errors anywhere in their child component tree, log them, and display a fallback UI instead of crashing the whole app.

๐Ÿ”น Key Points:
โœ… They only catch errors in class components (not functional components or event handlers).
โœ… They do not catch errors in async code, event handlers, or server-side rendering (SSR).

Create an Error Boundary Component (src/ErrorBoundary.js)

Since Error Boundaries must be class components, create a new file ErrorBoundary.js:

import React, { Component } from "react";

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

  static getDerivedStateFromError(error) {
    // Update state to show fallback UI
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    console.error("Caught an error:", error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div style={{ textAlign: "center", marginTop: "50px", color: "red" }}>
          <h2>๐Ÿšจ Oops! Something went wrong.</h2>
          <p>Try refreshing the page or contact support.</p>
        </div>
      );
    }

    return this.props.children;
  }
}

export default ErrorBoundary;

Try It Now

Use the Error Boundary in src/App.js

Wrap error-prone components with <ErrorBoundary>:

import React, { useState } from "react";
import ErrorBoundary from "./ErrorBoundary";

const BuggyComponent = () => {
  const [throwError, setThrowError] = useState(false);
  
  if (throwError) {
    throw new Error("Something went wrong!");
  }

  return (
    <div>
      <h2>Click the button to trigger an error</h2>
      <button onClick={() => setThrowError(true)}>Break the App ๐Ÿšจ</button>
    </div>
  );
};

function App() {
  return (
    <div style={{ textAlign: "center", marginTop: "50px" }}>
      <h1>โš ๏ธ React Error Boundaries</h1>

      <ErrorBoundary>
        <BuggyComponent />
      </ErrorBoundary>

    </div>
  );
}

export default App;

Try It Now

Why Use Error Boundaries?

โœ” Prevent full app crashes โ€“ only the failing component is affected.
โœ” Provide a user-friendly error message instead of a blank screen.
โœ” Log errors to services like Sentry or Firebase for debugging.