Error Boundaries
Definition
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.
Explain Like I'm New
Imagine a fuse box in your house. If you plug a faulty toaster into the kitchen wall, it blows the fuse. Without a fuse box, the entire house burns down (the whole React app turns into a blank white screen). An Error Boundary is the fuse box. It isolates the crash to just the kitchen, so the rest of the app keeps working, and shows a friendly 'Oops, the kitchen is broken' message.
Real World Example
If you have a dashboard with 5 different widgets, and one widget receives bad data from an API and throws an error during render, an Error Boundary wrapped around that specific widget ensures the other 4 widgets stay perfectly usable.
Common Use Cases
- •Preventing the entire application from unmounting due to a localized crash
- •Logging frontend errors to services like Sentry or LogRocket
- •Displaying graceful fallback UIs (like 'Something went wrong. Refresh?')
Interactive Example
Interview Questions
basic
- What is an Error Boundary in React?
- Can Error Boundaries catch errors in event handlers (like an onClick function)?
intermediate
- Which lifecycle methods must a Class component implement to become an Error Boundary?
- Why can't you write an Error Boundary using functional components and hooks?
advanced
- What types of errors do Error Boundaries NOT catch?
- How do Error Boundaries relate to the 'try/catch' block?
trick
- If a component throws an error, and the Error Boundary catches it, does the component's state survive?