Error Boundaries in React

📘 React.js 👁 43 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

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


Why Error Boundaries Are Important

Without error boundaries:

  • A single runtime error can crash the entire React app

With error boundaries:

  • Errors are isolated

  • Users see a friendly message

  • App remains usable


What Error Boundaries Catch

✅ Catches:

  • Errors during rendering

  • Errors in lifecycle methods

  • Errors in constructors of child components

❌ Does NOT catch:

  • Event handlers

  • Asynchronous code (setTimeout, fetch)

  • Server-side rendering errors

  • Errors inside the error boundary itself


How Error Boundaries Work

  • Must be class components

  • Use lifecycle methods:

    • getDerivedStateFromError

    • componentDidCatch


Basic Error Boundary Example

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, info) { console.error("Error caught:", error, info); } render() { if (this.state.hasError) { return <h2>Something went wrong.</h2>; } return this.props.children; } } export default ErrorBoundary;

Using Error Boundaries

Wrap components that may fail:

<ErrorBoundary> <Dashboard /> </ErrorBoundary>

Or wrap the entire app:

<ErrorBoundary> <App /> </ErrorBoundary>

Error Boundary with Custom Fallback UI

if (this.state.hasError) { return ( <div> <h2>Oops!</h2> <p>Please refresh the page.</p> </div> ); }

Error Boundaries and Functional Components

  • Error boundaries cannot be written with hooks

  • You must use class components

  • Libraries like react-error-boundary provide hook-friendly alternatives


Best Practices

  • Use multiple error boundaries

  • Wrap risky components (charts, third-party libs)

  • Log errors to monitoring services

  • Keep fallback UI simple and helpful


Common Use Cases

  • Lazy-loaded components

  • External APIs

  • Complex UI widgets


Key Takeaways

  • Error boundaries prevent app crashes

  • They catch render-time errors only

  • Must be implemented as class components

  • Improve app stability and UX


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes