What You'll Learn
You'll learn how error boundaries act as safety nets in component trees, catching rendering errors declaratively instead of letting your entire app crash.
The Component Tree Safety Net
In modern frameworks like React, your UI is a tree of components. When one component throws an error during rendering, it can break the entire tree—leaving users with a blank screen instead of a working app.
Error boundaries act like try-catch blocks for your component tree, but they work declaratively rather than imperatively. Just as a try-catch block in JavaScript catches runtime errors in a code block, an error boundary component catches rendering errors in any component below it in the tree.
The Declarative Difference
Traditional error handling uses imperative try-catch:
try {
riskyOperation();
} catch (error) {
handleError(error);
}
Error boundaries work declaratively by wrapping components:
<ErrorBoundary>
<UserProfile />
<CommentSection />
</ErrorBoundary>
If UserProfile or CommentSection crashes during rendering, the error boundary catches it and can display a fallback UI instead of breaking the whole page.
What They Catch
Error boundaries catch errors during:
- Component rendering
- Lifecycle methods
- Constructor calls in child components
What They Don't Catch
They cannot catch:
- Event handler errors (use regular
try-catch) - Asynchronous code errors
- Server-side rendering errors
- Errors in the boundary itself
Think of error boundaries as circuit breakers for your UI—they isolate failures to prevent cascading breakdowns, keeping the rest of your app functional.
Key Takeaway: Error boundaries provide declarative error handling for component trees, catching rendering failures and displaying fallback UIs instead of breaking your entire application.