What is an error boundary in React?

Why Interviewers Ask This

Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for React.js development. It reveals whether you understand the building blocks that more complex concepts rely on.

Answer

An error boundary is a React class component that catches JavaScript errors anywhere in its child component tree and displays a fallback UI instead of crashing the entire application. Without error boundaries, a runtime error in any component crashes the whole React app. Implement by defining static getDerivedStateFromError(error) (to trigger the fallback render) and/or componentDidCatch(error, info) (to log errors). Example: class ErrorBoundary extends React.Component { state = { hasError: false }; static getDerivedStateFromError() { return { hasError: true }; } render() { return this.state.hasError ? <FallbackUI /> : this.props.children; } }. Usage: <ErrorBoundary><MyComponent /></ErrorBoundary>. Limitations: error boundaries do NOT catch: errors in event handlers (use try/catch), asynchronous errors (setTimeout, Promises), errors in the error boundary itself, and errors during server-side rendering. Note: there is no function-component equivalent — error boundaries must be class components. Libraries like react-error-boundary provide a ready-made wrapper.

Pro Tip

Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a React.js codebase.