Building Fallback UI with react-error-boundary
Building Fallback UI with react-error-boundary
1. Modernizing Error Boundaries with react-error-boundary
While writing custom class-based Error Boundaries is educational, maintaining class components in an otherwise 100% functional modern React codebase creates friction.
The open-source community created react-error-boundary, the industry-standard package maintained by Brian Vaughn (former React core team member).
react-error-boundary provides:
- A declarative
<ErrorBoundary>component with rich functional fallback support. - The
useErrorBoundary()hook for triggering and resetting boundaries from functional components. - Direct support for resetting state when dependencies or route parameters change.
2. Installation
3. Creating a Reusable Fallback Component
A fallback component receives error and resetErrorBoundary as props:
4. Wrapping Components with Reset Keys
A powerful feature of react-error-boundary is resetKeys.
If an error occurred because a specific course or ID was invalid, when the user navigates to a different course, the boundary automatically resets itself without requiring a page refresh!
5. Triggering Boundaries from Async Code with showBoundary()
Normally, Error Boundaries cannot catch errors inside async functions or event handlers.
react-error-boundary provides the useErrorBoundary() hook, whose showBoundary(err) method allows you to explicitly forward asynchronous errors into the nearest Error Boundary:
Practice Quiz
<ErrorBoundary FallbackComponent={...}>?resetKeys prop in react-error-boundary?try...catch block in an event handler be sent to an Error Boundary?Reporting Client Errors to Monitoring Services
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| React Error Boundaries and Lifecycle Catching | Reporting Client Errors to Monitoring Services |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.