withErrorBoundary Higher-Order Component
What you'll learn: How to wrap components with error boundaries using a clean, declarative HOC pattern instead of manually nesting JSX.
The Composition Problem
So far, you've wrapped components with <ErrorBoundary> tags directly in your JSX. That works, but it can get verbose when you need to wrap many components, especially if you're exporting components that should always be protected. The withErrorBoundary HOC gives you a cleaner composition pattern.
How withErrorBoundary Works
withErrorBoundary is a higher-order component that wraps your component in an ErrorBoundary automatically. Instead of:
<ErrorBoundary FallbackComponent={ErrorFallback}>
<MyComponent />
</ErrorBoundary>
You create a pre-wrapped version:
import { withErrorBoundary } from 'react-error-boundary';
const SafeMyComponent = withErrorBoundary(MyComponent, {
FallbackComponent: ErrorFallback,
onError: logErrorToService,
resetKeys: ['userId']
});
// Now just use it directly:
<SafeMyComponent userId={userId} />
Think of It Like Pre-Packaging
It's like buying a phone already in a protective case versus buying them separately. The HOC lets you export components that are already protected, so consumers don't need to remember to wrap them.
When to Use It
This pattern shines when:
- You want to export protected components from modules
- You're wrapping many components with identical boundary config
- You prefer functional composition over JSX nesting
- You're building component libraries that should be resilient by default
All the same props work: FallbackComponent, onError, onReset, resetKeys — you just pass them as the second argument to withErrorBoundary.
Key Takeaway: withErrorBoundary provides a cleaner, more composable way to wrap components with error boundaries, perfect for creating pre-protected exports and reducing JSX nesting.