Overview
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 entire application. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.Creating an Error Boundary
A class component becomes an error boundary if it definesstatic getDerivedStateFromError() or componentDidCatch() lifecycle methods.
Basic Error Boundary
Lifecycle Methods
getDerivedStateFromError
componentDidCatch
error- The error that was thrownerrorInfo- An object with acomponentStackproperty containing stack trace information
Advanced Error Boundary
Usage Patterns
Wrapping Top-Level Routes
Multiple Error Boundaries
Custom Fallback UI
Error Boundaries with Async Data
Error Boundaries vs Try-Catch
Logging Errors
Integrate with error monitoring services:Error Boundaries in Development vs Production
Best Practices
- Use multiple error boundaries: Don’t wrap your entire app in one boundary
- Provide recovery mechanisms: Include “Try Again” or “Reload” buttons
- Log errors properly: Always log to monitoring services in production
- Show user-friendly messages: Don’t expose technical details in production
- Reset error boundaries: Use keys to reset boundaries when needed
- Handle async errors: Use try-catch for promises and async operations
- Test error scenarios: Explicitly test that error boundaries work
Granular Error Boundaries
Limitations
Error boundaries have several limitations:- Only class components: Error boundaries must be class components (no hook equivalent yet)
- Render errors only: Don’t catch errors in event handlers or async code
- No self-catching: Can’t catch errors thrown in the boundary itself
- No SSR errors: Don’t catch errors during server-side rendering
See Also
- Component API - Class component lifecycle methods