React Error Boundaries and Render Error Handling

Error boundaries let a React component catch certain errors thrown while rendering, in lifecycle methods, or in constructors of descendant components. They provide a controlled fallback UI instead of allowing the affected component subtree to fail silently or take down the entire rendered interface.

An error boundary is a React component that implements `static getDerivedStateFromError` and/or `componentDidCatch`. When a descendant throws during rendering or a related React lifecycle phase, React can move rendering to the boundary's fallback state.

The boundary handles errors from its child tree, not errors thrown by the boundary itself. A common pattern is to store an `hasError` flag in state and return fallback UI when that flag becomes true.

Error boundaries do not catch every kind of JavaScript error. In particular, they do not handle errors from event handlers, asynchronous callbacks such as `setTimeout`, server-side rendering, or errors thrown by the boundary component itself. Those cases need their own handling mechanisms.

For a frontend application, boundaries are useful around meaningful UI regions such as routes, dashboards, or independent widgets. The goal is graceful degradation: one broken subtree can show a fallback while unrelated parts of the application remain usable.

Key points

Interview questions

How would you decide where to put error boundaries in a frontend application?

I would place them around meaningful independent UI regions where a failure should not prevent unrelated content from rendering. Routes, dashboards, or complex widgets are common candidates. I would avoid relying on a single application-wide boundary when finer-grained isolation provides a better user experience.

What is an error boundary in React?

An error boundary is a React component that catches certain errors thrown by descendant components during rendering and related lifecycle execution. It can then render fallback UI instead of the failed subtree. Class components implement the boundary API through `getDerivedStateFromError`, `componentDidCatch`, or both.

How does `getDerivedStateFromError` differ from `componentDidCatch`?

`getDerivedStateFromError` is used to derive state from the failure so React can render fallback UI on the next render. `componentDidCatch` runs for side effects after an error has been caught. A typical implementation uses the first for the user-facing fallback and the second for logging or reporting.

What errors do React error boundaries not catch?

They do not catch errors from event handlers, asynchronous callbacks, server-side rendering, or errors thrown by the boundary itself. Event-handler failures therefore need explicit handling in the event code or another error-reporting mechanism. Boundaries are specifically tied to errors React encounters in the descendant rendering and lifecycle process.