React › Error Boundaries

What is an error boundary in React and why is it useful?

Beginner

Answer

An error boundary is a special component that catches JavaScript errors happening anywhere in its child components, and shows a friendly fallback message instead of letting the entire app crash and show a blank white screen to the user.
class ErrorBoundary extends React.Component {
  state = { hasError: false };
  static getDerivedStateFromError() {
    return { hasError: true };
  }
  render() {
    if (this.state.hasError) return <p>Something went wrong, please try again</p>;
    return this.props.children;
  }
}

<ErrorBoundary>
  <ProductList />
</ErrorBoundary>
Real-world example An online store wraps its product list in an error boundary, so if one product's data is broken and causes an error, the customer sees a friendly message instead of the whole website going completely blank.

Common follow-ups: What kinds of errors does an error boundary fail to catch, such as errors inside event handlers?;Can you nest multiple error boundaries in different parts of an app?