React Error Boundaries: Catching Runtime Errors & Fallback UI

In JavaScript, an unhandled exception thrown inside a component's render method used to corrupt React's internal state and cause the entire web page to unmount, leaving the user with an empty white screen. Error Boundaries provide a protective safety net: if a single card or widget crashes, only that card displays a friendly fallback message while the rest of the application remains fully interactive.

Implementing a Reusable Error Boundary Class Component

// src/components/ErrorBoundary.jsx
import React, { Component } from 'react';

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

  // 1. Update state so next render shows fallback UI
  static getDerivedStateFromError(error) {
    return { hasError: true, errorMessage: error.message };
  }

  // 2. Log error details to an external monitoring service (e.g. Sentry)
  componentDidCatch(error, errorInfo) {
    console.error('ErrorBoundary caught an unhandled error:', error, errorInfo);
  }

  handleRetry = () => {
    this.setState({ hasError: false, errorMessage: '' });
  };

  render() {
    if (this.state.hasError) {
      return (
        <div className="error-fallback-card" style={{ padding: '20px', border: '1px solid #ef4444', borderRadius: '8px', background: '#fef2f2' }}>
          <h3 style={{ color: '#b91c1c', marginTop: 0 }}>Something went wrong in this widget.</h3>
          <p style={{ color: '#7f1d1d' }}>{this.state.errorMessage}</p>
          <button onClick={this.handleRetry} style={{ background: '#5dbe59', color: '#fff', border: 'none', padding: '8px 16px', borderRadius: '4px', cursor: 'pointer' }}>
            Retry Component
          </button>
        </div>
      );
    }

    return this.props.children;
  }
}

export default ErrorBoundary;

Wrapping Vulnerable Components:

function Dashboard() {
  return (
    <div className="dashboard-grid">
      <Navbar />
      
      {/* Protected Widget */}
      <ErrorBoundary>
        <LiveStockFeed />
      </ErrorBoundary>

      <Footer />
    </div>
  );
}

Next Step: Fragments & StrictMode

Now let us examine clean DOM tree preservation in React Fragments & StrictMode.

Explore Related React JS Tutorials

Accelerate your React mastery by studying these tightly connected core tutorials:

Suspense & Error Boundaries →

Graceful fallback UI for async component loading.

Class Lifecycle Boundaries →

getDerivedStateFromError and componentDidCatch.

Testing Fallback UIs →

Simulating component crashes using React Testing Library.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!