Error Boundaries are a React feature used to catch JavaScript errors in the component tree and prevent the whole app from crashing. They are a very common interview question, especially for React mid-level roles.
Definition
An Error Boundary is a React component that catches runtime errors in its child components during rendering, lifecycle methods, and constructors, and displays a fallback UI instead of breaking the entire application.
Why Error Boundaries are needed?
Normally, if a component throws an error:
-
The entire React component tree unmounts
-
The user sees a blank screen
Error Boundaries solve this by:
-
Catching the error
-
Logging it
-
Showing a fallback UI (like “Something went wrong”)
How Error Boundaries work
Error Boundaries catch errors in:
-
Rendering phase
-
Lifecycle methods
-
Constructors of child components
❌ They do NOT catch:
-
Event handlers
-
Async code (like
setTimeout, promises) -
Server-side rendering errors
Required lifecycle methods
A class component becomes an Error Boundary when it implements:
1. static getDerivedStateFromError(error)
Used to update state so UI can show fallback.
2. componentDidCatch(error, info)
Used for logging errors.
Example
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
console.log("Error logged:", error, info);
}
render() {
if (this.state.hasError) {
return <h2>Something went wrong.</h2>;
}
return this.props.children;
}
}
Usage:
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>
Key Interview Points
-
Error Boundaries are class components only (not functional components yet, though patterns exist)
-
They prevent entire app crash due to one component failure
-
They act like a try-catch for React components
-
They should be placed strategically (not everywhere)
Common Misconceptions
❌ They catch all errors in React
✔️ No, they only catch rendering/lifecycle errors in children
❌ They work in functional components
✔️ Not directly (you need class component or libraries like react-error-boundary)
Real-world usage
-
Page-level error handling
-
Widget-level isolation (dashboard cards)
-
Preventing blank screens in production apps
One-line interview summary
Error Boundaries in React are components that catch rendering errors in child components and display a fallback UI instead of crashing the whole application.
