Blog>
Snippets

Retry Mechanism with Error Boundary

Implement an Error Boundary around a resource-intensive component that provides a retry button after an error occurs.
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  retry = () => {
    this.setState({ hasError: false });
    // Optionally, you can reset other states or resources
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return (
        <div>
          <p>Something went wrong.</p>
          <button onClick={this.retry}>Retry</button>
        </div>
      );
    }
    return this.props.children;
  }
}
Defines an ErrorBoundary component that wraps a resource-intensive component. It displays a retry button if an error occurs, which, when clicked, tries to re-render the children components.
class ResourceIntensiveComponent extends React.Component {
  // ... Resource-intensive operations and potential error throwing
}
This represents the resource-intensive component that might throw an error. Put your logic here.
function App() {
  return (
    <ErrorBoundary>
      <ResourceIntensiveComponent />
    </ErrorBoundary>
  );
}
This is the root component that utilizes the ErrorBoundary to wrap around the ResourceIntensiveComponent.