CodePark/ questions / Error handling
START PRACTICINGPRACTICE
Frontend question · React › Error handling

What is an error boundary, how do you create one, and what errors does it not catch?

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 ? this.props.fallback : this.props.children;
  }
}

An error boundary is a component that catches errors in its children and shows a fallback UI instead. It catches errors thrown:

  • while rendering its children
  • in lifecycle methods below it
  • in effects below it

Without a boundary, an uncaught rendering error removes the entire React tree, and the user sees a blank page.

There is still no hook for this. You write a class component with two methods:

  • static getDerivedStateFromError switches to the fallback.
  • componentDidCatch is optional and logs the error.

Or you use a library like react-error-boundary.

It does not catch errors:

  • in event handlers
  • in asynchronous code, such as setTimeout or a promise callback outside rendering
  • during server rendering
  • in the boundary itself

For handlers, use try/catch and store the error in state. Place boundaries around independent sections, so one failure does not break the rest of the page.

  • An error boundary catches render, lifecycle and effect errors in its subtree.
  • You build one as a class with getDerivedStateFromError and componentDidCatch, or use a library.
  • It does not catch errors from event handlers or async code.
  • It does not catch server rendering errors or its own errors.
  • Place boundaries around independent sections of the UI.