Lesson 31 — Error Boundaries in React (Handle UI Crashes Gracefully)

🧭 Introduction

In real-world applications, bugs and unexpected errors are unavoidable. A small JavaScript error in one component can crash the entire React application, showing a blank screen to users.

To prevent this and provide a better user experience, React offers a powerful concept called Error Boundaries.

In this lesson, you will learn:

  • What Error Boundaries are
  • Why they are important
  • How Error Boundaries work
  • How to create an Error Boundary
  • Real-world usage examples
  • Best practices and FAQs

❓ What are Error Boundaries in React?

Error Boundaries are special React components that:

Catch JavaScript errors in their child component tree and display a fallback UI instead of crashing the whole app.

They catch errors during:

  • Rendering
  • Lifecycle methods
  • Constructors of child components

🚫 What Error Boundaries Do NOT Catch

Error Boundaries do not catch errors in:
❌ Event handlers
❌ Asynchronous code (setTimeout, fetch)
❌ Errors thrown inside the error boundary itself
❌ Server-side rendering

👉 These must be handled using try-catch.


🧠 Why Error Boundaries Are Important?

Without Error Boundaries ❌

  • Entire app crashes
  • Blank screen for users
  • Poor user experience

With Error Boundaries ✅

  • App remains stable
  • Only broken component is replaced
  • User sees a friendly error message

🧩 How Error Boundaries Work

Error Boundaries are implemented using class components, because:

  • Hooks do not support error boundaries yet

They use two lifecycle methods:

  • static getDerivedStateFromError()
  • componentDidCatch()

🛠 Creating a Simple Error Boundary

📄 ErrorBoundary.jsx

import React from "react";

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

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

  componentDidCatch(error, errorInfo) {
    console.error("Error caught:", error, errorInfo);
  }

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

    return this.props.children;
  }
}

export default ErrorBoundary;


🧩 Using Error Boundary in App

📄 App.jsx

import ErrorBoundary from "./ErrorBoundary";
import Dashboard from "./Dashboard";

function App() {
  return (
    <ErrorBoundary>
      <Dashboard />
    </ErrorBoundary>
  );
}

export default App;

✔ If Dashboard crashes, the app does not break completely
✔ Fallback UI is shown instead


🧪 Example: Component That Throws Error

📄 BuggyComponent.jsx

const BuggyComponent = ({ value }) => {
  if (!value) {
    throw new Error("Value is missing!");
  }

  return <h3>Value: {value}</h3>;
};

export default BuggyComponent;

Wrap it with Error Boundary to prevent app crash.


🧠 Real-World Usage Patterns

✅ Wrap entire app
✅ Wrap individual routes
✅ Wrap critical UI sections (Dashboard, Charts)

Example:

<ErrorBoundary>
  <Dashboard />
</ErrorBoundary>


🆚 Error Boundary vs try-catch

FeatureError Boundarytry-catch
Catches render errors
UI fallback
Event handler errors
React lifecycle errors

⚠ Common Mistakes

❌ Expecting Error Boundary to catch async errors
❌ Wrapping too much UI unnecessarily
❌ Forgetting fallback UI
❌ Using functional components for error boundaries


🎯 Best Practices

✅ Use Error Boundaries at logical boundaries
✅ Keep fallback UI simple and user-friendly
✅ Log errors for debugging
✅ Combine with monitoring tools (Sentry, LogRocket)


❓ FAQs — Error Boundaries in React

🔹 Are Error Boundaries mandatory?

Not mandatory, but highly recommended for production apps.


🔹 Can I use Error Boundaries with functional components?

No. Error Boundaries must be class components.


🔹 Can one Error Boundary handle multiple components?

Yes. It catches errors in all child components.


🔹 Do Error Boundaries catch API errors?

No. Handle API errors using try-catch.


🔹 Can I reset an Error Boundary?

Yes, by controlling state or remounting it.


🧠 Quick Recap

✔ Error Boundaries prevent full app crashes
✔ They catch render & lifecycle errors
✔ Implemented using class components
✔ Essential for production-ready apps


🎉 Conclusion

Error Boundaries are a critical safety net in React applications. They protect your app from crashing completely and help deliver a stable and professional user experience, even when bugs occur.

After this lesson, your React apps are more resilient and production-ready 🚀


👉 Next Lesson (SECTION 6):
Lesson 32 — React Profiler & Performance Debugging

Leave a Comment