AceDevHub
Intermediate React Interview QuestionsIntermediateConcept

React · Question 69

What is an Error Boundary in React, and what errors does it handle?

Direct answer

An Error Boundary is a React component that catches supported errors from descendant rendering, shows fallback UI, and can log the failure instead of letting that part of the UI disappear.

ErrorBoundary.jsx
class ErrorBoundary extends React.Component {
  state = { hasError: false };

  static getDerivedStateFromError() {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    reportError(error, info);
  }

  render() {
    if (this.state.hasError) {
      return <Fallback />;
    }
    return this.props.children;
  }
}

React's built-in class lifecycle APIs getDerivedStateFromError and componentDidCatch are the traditional primitives for implementing an Error Boundary.