HuntExams Academy logo
ReactAdvanced#errors

What is an error boundary?

Answer

A class component implementing componentDidCatch/getDerivedStateFromError that catches render-time errors in its subtree and shows a fallback UI instead of a blank page. It does not catch event handler or async errors.

Example

class Boundary extends React.Component {
  state = { failed: false };
  static getDerivedStateFromError() { return { failed: true }; }
  render() { return this.state.failed ? <p>Something broke</p> : this.props.children; }
}

Detailed explanation

An error boundary is a React component that contains failures in its descendant component tree and displays a fallback UI instead of letting the failure remove the entire application UI. It catches errors thrown during rendering, constructors, and lifecycle methods of descendants. For example, placing a boundary around a dashboard widget lets the surrounding navigation and other widgets remain usable if that widget crashes. Boundaries are useful for unexpected programming failures; ordinary states such as validation errors or an unsuccessful API response should usually have explicit handling in the component.

A boundary is implemented as a class component using static getDerivedStateFromError(error), componentDidCatch(error, info), or both. getDerivedStateFromError runs during React’s render phase and returns state that selects the fallback UI, so it must remain pure. componentDidCatch runs during the commit phase and is suitable for reporting the error; its info argument includes a component stack. In the supplied example, getDerivedStateFromError changes failed to true, and render subsequently returns the message instead of children. That is sufficient for a basic fallback boundary; componentDidCatch can be added for diagnostics.

When a descendant throws, React looks for an eligible boundary above it and attempts recovery through that boundary. A boundary cannot catch errors thrown by its own rendering or lifecycle methods: those require an ancestor boundary. It also does not catch errors from event handlers, ordinary asynchronous callbacks such as setTimeout, or server-side rendering. Handle event-handler failures with local try/catch and asynchronous failures with promise rejection handling or try/catch around await. A surrounding JavaScript try/catch does not replace a boundary because React renders child components separately from the parent creating their elements.

Interviewers usually expect both the mechanism and these limits. Choose boundary placement according to what can fail independently, such as a route, panel, or editor, rather than wrapping every small component. Provide a useful fallback and an intentional reset strategy, such as remounting the boundary with a changed key after addressing the cause. React has no built-in Hook for defining an error boundary directly, although libraries expose function-friendly wrappers around boundary implementations.

Key points to remember

  • Error boundaries catch descendant rendering, constructor, and lifecycle errors.
  • getDerivedStateFromError selects fallback state; componentDidCatch supports error reporting.
  • They do not catch their own errors, event-handler errors, ordinary async callback errors, or server-rendering errors.
  • Place boundaries around independently recoverable UI sections to contain failures.
  • A fallback needs an intentional recovery strategy; resetting state alone does not fix the cause.

Common mistakes candidates make

  • Assuming an error boundary automatically catches rejected fetch promises or click-handler exceptions.
  • Performing logging or other side effects inside getDerivedStateFromError instead of componentDidCatch.
  • Offering a retry button that resets the boundary without considering whether the same failure will immediately recur.

Likely follow-up questions

Can a function component implement an error boundary?

React does not provide a built-in Hook equivalent to the error-boundary lifecycle methods. A function component can use a library-provided boundary or render a custom class-based boundary.

How should an error boundary handle a failed API request?

It does not directly catch an ordinary rejected request promise. Handle the rejection and show an explicit error state; if the component instead throws an error during a subsequent render, an ancestor boundary can catch that render error.

How do you reset an error boundary?

A custom boundary can expose an action that clears its error state, or its parent can change its key to remount it. Recovery should also address the failing data or condition, otherwise rendering the children may throw again.

Interview tip: Define the boundary, explain the two lifecycle methods using the example, and finish with its exclusions and one practical placement decision.

Related Interview Questions

1
ReactIntermediate#lifecycle#hooks

How does the component lifecycle map to hooks?

Open
2
ReactAdvanced#performance

What is lazy loading and code splitting in React?

Open
3
ReactAdvanced#performance#data

What is Suspense?

Open