React Error Boundaries: Interview Guide
⚛ ری‌اکت

React Error Boundaries: Interview Guide

Catch render errors, show fallback UI, and know what error boundaries cannot catch.

BugCast Admin··۵ دقیقه مطالعه

Error boundaries are class components (or libraries) that catch JavaScript errors in child render/lifecycle and display fallback UI instead of crashing the whole app.

Common Interview Questions

Q: How do you implement an error boundary?

Answer: Use getDerivedStateFromError for fallback state and componentDidCatch for logging. There is no hooks equivalent yet.


class ErrorBoundary extends React.Component {
  state = { hasError: false };
  static getDerivedStateFromError() {
    return { hasError: true };
  }
  componentDidCatch(error, info) {
    logError(error, info.componentStack);
  }
  render() {
    return this.state.hasError
      ? <h1>Something went wrong.</h1>
      : this.props.children;
  }
}

Q: What do error boundaries NOT catch?

Answer: Event handler errors, async code (setTimeout, promises), server-side rendering errors, or errors in the boundary itself. Use try/catch in handlers for those.

Q: Where should boundaries be placed?

Answer: Around route-level sections, risky third-party widgets, and data-heavy trees — granular enough to isolate failures without hiding all UI.

Q: React 19 error handling updates?

Answer: Discuss react-error-boundary package and evolving patterns. Core idea unchanged: declarative fallback for render-phase failures.

Key Points for Interviews

  • Only class components can be error boundaries today

  • Catch render/lifecycle errors in children

  • Not a replacement for try/catch in async/event code

  • Log to Sentry/Datadog in componentDidCatch

  • Granular boundaries improve resilience UX

#error-boundaries#errors#interview

مطالب مرتبط