Recover from render errors

19.3

Put an error boundary around a part of the UI so a render failure can show a clear message in that area.

On this page

Render a fallback

A class boundary can turn a render error in a child into fallback UI. Use getDerivedStateFromError to switch what renders. componentDidCatch can report the error and component stack to your logging service.

import React, { Component } from "react";

class SectionBoundary extends Component {
  state = { failed: false };

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

  render() {
    return this.state.failed
      ? <p role="alert">This section could not load.</p>
      : this.props.children;
  }
}

export default SectionBoundary;

Handle other failures at the source

Handle rejected fetch calls and event handler failures where they occur. A boundary does not catch its own errors or errors from server rendering. Change its key when switching to a different record if you want that record to start with a fresh boundary.

<SectionBoundary key={productId}>
  <StockPanel productId={productId} />
</SectionBoundary>

Official references