Course contentsShow
← React
Lesson 1304 of 2,39633. Error BoundariesFree lesson

Error Boundary Props and Customization

Accepting fallback and onError props to make error boundaries reusable across different parts of your app.

Error Boundary Props and Customization

What you'll learn: How to make your error boundaries reusable by accepting fallback and onError props, letting different parts of your app handle errors differently.

So far, you've built error boundaries that display a hardcoded fallback UI and maybe log errors in a specific way. But what if different parts of your app need different error handling? A critical checkout flow might need a "retry payment" button, while a sidebar widget could just hide itself gracefully.

The solution is to treat your error boundary like any other component: accept props that customize its behavior.

The Reusable Pattern

Instead of hardcoding the fallback UI, accept it as a prop:

class ErrorBoundary extends React.Component {
  state = { hasError: false, error: null };

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

  componentDidCatch(error, errorInfo) {
    // Use the custom onError handler if provided
    this.props.onError?.(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // Use custom fallback if provided, otherwise default
      return this.props.fallback || <h1>Something went wrong.</h1>;
    }

    return this.props.children;
  }
}

Using It Flexibly

Now you can customize per feature:

<ErrorBoundary 
  fallback={<CheckoutErrorScreen />}
  onError={(error, info) => logToPaymentService(error, info)}
>
  <CheckoutFlow />
</ErrorBoundary>

<ErrorBoundary 
  fallback={<div>Widget unavailable</div>}
  onError={(error) => console.warn('Widget failed:', error)}
>
  <SidebarWidget />
</ErrorBoundary>

Key Takeaway: By accepting fallback and onError props, you transform your error boundary from a single-use component into a reusable error-handling tool that adapts to different contexts across your application.