πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
Search courses…
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

Error Boundaries

React Patterns🟒 Free Lesson

Advertisement

Error Boundaries

Catching errors, fallback UIs, error reporting, and graceful degradation.

Overview

Error boundaries catch JavaScript errors in their child component tree and display fallback UI.

Key Concepts

  • componentDidCatch β€” Catches errors during rendering
  • getDerivedStateFromError β€” Updates state when error occurs
  • Fallback UI β€” User-friendly error display
  • Error Reporting β€” Log errors to monitoring services
  • Granular Boundaries β€” Wrap specific sections, not entire app

Code Examples

import { Component } from 'react';

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

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

  componentDidCatch(error, errorInfo) {
    console.error('Error caught:', error, errorInfo);
    // Send to error reporting service
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="error-fallback">
          <h2>Something went wrong</h2>
          <p>{this.state.error?.message}</p>
          <button onClick={() => this.setState({ hasError: false })}>
            Try again
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

// Usage
function App() {
  return (
    <ErrorBoundary>
      <Header />
      <main>
        <ErrorBoundary>
          <Sidebar />
        </ErrorBoundary>
        <Content />
      </main>
    </ErrorBoundary>
  );
}

Practice

Create an error boundary that logs errors and provides a retry mechanism.

⭐

Premium Content

Error Boundaries

Unlock this lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
πŸ’ΌInterview Prep
πŸ“œCertificates
🀝Community Access

Already a member? Log in

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement