Skip to main content

Error Boundaries

React Router provides automatic error handling through Error Boundaries that catch errors from loaders, actions, and component rendering. This enables graceful error recovery without crashing your entire app.

Basic Error Boundary

Every route can export an ErrorBoundary component:

Error Sources

Error boundaries catch errors from multiple sources:

Loader Errors

Action Errors

Render Errors

Error Types

Route Error Response

Thrown Response objects with status codes:
Handling in ErrorBoundary:

Regular Errors

Error Boundary Hierarchy

Errors bubble up to the nearest route with an ErrorBoundary:

Root Error Boundary

Always provide a root-level error boundary:
From lib/dom/ssr/errorBoundaries.tsx:73, the default error boundary:

Error Recovery

Users can recover from errors by navigating:
From lib/hooks.tsx:1030, error boundaries reset on navigation:

Contextual Error Messages

Error Logging

Error Boundaries vs Try/Catch

Validation vs Errors

Custom Error Classes

Error Boundary Component

From lib/hooks.tsx:1011, the RenderErrorBoundary implementation:

Best Practices

  1. Always provide a root ErrorBoundary - Last line of defense
  2. Throw Response objects - Use proper HTTP status codes
  3. Use specific error boundaries - Contextual error handling
  4. Don’t catch unnecessarily - Let errors bubble to boundaries
  5. Provide recovery options - Links to go back or home
  6. Log errors - Track issues in production
  7. Return validation errors - Don’t throw for expected failures
  8. Include helpful context - Show what went wrong and why
  9. Test error scenarios - Ensure boundaries work as expected
  10. Keep error UI accessible - Include Scripts and basic HTML structure