Error Boundary — Error Handling
Error Boundary — Error Handling
💡 Why Should You Learn This?
Concept
An Error Boundary is an error-isolation mechanism in React that prevents a single error in the component tree from crashing the entire app, showing a fallback UI instead. In production, it is essential for protecting the user experience and maintaining a stable service.
Why Does It Matter?
In a live production environment, runtime errors caused by third-party library bugs or unexpected data can turn the entire screen into a blank white page. With an Error Boundary in place, only the affected section is replaced with an error UI, allowing users to continue using the rest of the service. Error Boundaries can also be integrated with error-reporting tools to aid in incident detection and debugging.
Core Concept
An Error Boundary works like a firewall in a building. Even if a fire breaks out in one room, the firewall prevents it from spreading to the others. In React, an Error Boundary 'isolates' errors that occur in a specific part of the component tree so the entire app does not go down, and shows users an appropriate fallback UI.
Key Points
- ▸Can only be implemented in class components (as of React 19)
- ▸Only catches errors during rendering and in lifecycle methods of child components
- ▸Does NOT catch errors in event handlers, asynchronous code, or server-side rendering
- ▸Integrate with error logging for production monitoring
💡 ⚠️ Common Mistakes
- ▸Placing Error Boundaries only at the very top level, causing the entire page to be replaced with a fallback UI when any error occurs
- ▸Assuming Error Boundaries will also catch errors in event handlers or asynchronous code (a separate try-catch is required for those)
- ▸Showing only a fallback UI without any error logging, making it difficult to diagnose problems in production
💡 🎯 Interview Prep
Q: Explain the difference between errors that an Error Boundary can catch and those it cannot.
Q: How would you strategically position Error Boundaries in your application?
Q: What is the difference between an Error Boundary and try-catch?
Hint: Error Boundaries only catch errors during rendering — events and async code require try-catch. Use strategic placement to isolate errors and protect UX. Distinguish the roles of getDerivedStateFromError and componentDidCatch. Emphasize the importance of integrating error reporting and monitoring.