Error Boundaries — React Technical Interview Questions & Answers

Error Boundaries

Error Boundaries

  • An error boundary is a class (or a small library wrapper) that catches render errors in its child tree and shows a fallback UI instead of a white screen. getDerivedStateFromError + componentDidCatch. It does not catch errors in event handlers, async code, or the boundary’s own render — those still need try/catch / error state.
  • Function components cannot be error boundaries by themselves. react-error-boundary is the usual wrapper. Put a boundary around a risky widget, not necessarily the whole app only.
  • Error Boundaries — child throw during render → Something broke. Click handler errors still need try/catch.

Technical Interview Tip: What it catches vs doesn’t. Class-only core API.

Code Examples for Error Boundaries

Example

// Error boundary
import { Component } from "react";

class Guard extends Component {
  state = { crash: false };
  static getDerivedStateFromError() { return { crash: true }; }
  componentDidCatch(err) { console.error(err); }
  render() {
    if (this.state.crash) return <p>Something broke.</p>;
    return this.props.children;
  }
}

Error Boundaries — child throw during render → Something broke. Click handler errors still need try/catch.

How to Explain Error Boundaries to an Interviewer

Does an error boundary catch a fetch() reject?

No

Can a function component be an error boundary alone?

No