MyInternships.in

Performance & Patterns

React Error Boundaries

An error boundary is a component that catches JavaScript errors thrown while rendering its subtree, logs them, and shows a fallback instead of unmounting the whole application. Boundaries must be class components — there is still no hook equivalent.


What is Error Boundaries in React?

An error boundary is a component that catches JavaScript errors thrown while rendering its subtree, logs them, and shows a fallback instead of unmounting the whole application. Boundaries must be class components — there is still no hook equivalent.

Why Error Boundaries matters

Without one, a single render error blanks the entire page. With one, the failure is contained to a section and the rest of the app keeps working.

Error Boundaries example

A reusable boundary
JSX
class ErrorBoundary extends React.Component {
  state = { hasError: false };

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

  componentDidCatch(error, info) {
    logToService(error, info.componentStack);
  }

  render() {
    if (this.state.hasError) return this.props.fallback ?? <p>Something went wrong.</p>;
    return this.props.children;
  }
}

<ErrorBoundary fallback={<ChartError />}>
  <SalaryChart />
</ErrorBoundary>

How this works

getDerivedStateFromError switches to the fallback; componentDidCatch is where you report the error. Together they turn a crash into a contained, observable failure.

Key points to remember

  • They do NOT catch errors in event handlers, async code, timers, or server rendering.
  • Use try/catch inside handlers and .catch on promises for those cases.
  • react-error-boundary provides a hook-friendly wrapper with a reset function.

Common mistakes with Error Boundaries

  • Expecting a boundary to catch an error thrown inside onClick — it will not.
  • Placing one boundary at the root only, so any failure still blanks the page.

React Error Boundaries— Interview Questions & FAQs

Why do error boundaries have to be class components?+

The lifecycle methods they rely on — getDerivedStateFromError and componentDidCatch — have no hook equivalent yet. Use the react-error-boundary package if you want to avoid writing a class.

Do error boundaries catch errors in event handlers?+

No. Handlers run outside rendering, so React cannot intercept them. Wrap the handler body in try/catch and set error state yourself.

Related React Topics

Keep learning with these closely related lessons.

Ready to use your React skills?

Find verified React internships and fresher developer jobs across India.

Browse React Internships