React Error Boundaries and Lifecycle Catching
React Error Boundaries and Lifecycle Catching
1. The Vulnerability of Uncaught UI Errors
In client-side React applications, a JavaScript runtime error inside any component's render function (such as attempting to read a property of undefined: student.profile.avatar) corrupts React's internal Virtual DOM tree.
In standard React:
For users, a blank white screen looks like a complete system crash with zero explanation or recovery path.
2. What is an Error Boundary?
An Error Boundary is a React component that catches JavaScript errors anywhere in its child component tree, logs the errors, and displays a friendly fallback UI instead of crashing the entire application.
Error Boundaries catch errors during:
- Rendering
- Lifecycle methods
- Constructors of class components beneath them in the tree
3. Why Error Boundaries Must Be Class Components
As of React 18, Error Boundaries must be implemented as Class Components. There is currently no functional hook equivalent for componentDidCatch or getDerivedStateFromError.
An Error Boundary class defines one or both of these lifecycle methods:
- 1
static getDerivedStateFromError(error): Renders a fallback UI upon an error. - 2
componentDidCatch(error, errorInfo): Logs error information to an external telemetry service (e.g. Sentry, Datadog).
4. What Error Boundaries Do NOT Catch
Error Boundaries do NOT catch errors in:
- Event Handlers: (e.g. errors inside
onClick). Use standardtry...catchblocks for event handlers. - Asynchronous Code: (
setTimeout,requestAnimationFrame, raw unhandled Promise rejections). - Server-Side Rendering (SSR): Errors occurring during server HTML streaming.
- Errors thrown inside the Error Boundary component itself (rather than in its children).
Practice Quiz
Building Fallback UI with react-error-boundary
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Composing Multiple Hooks and Custom Hook Testing | Building Fallback UI with react-error-boundary |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.