React › Error Boundaries

How would you build a reusable error boundary that lets the user retry after an error occurs?

Advanced

Answer

You add a button inside the fallback view that resets the error boundary's state back to no error, allowing React to attempt rendering the children again from scratch. This gives users a way to recover from a temporary problem without needing to reload the entire page.
class ErrorBoundary extends React.Component {
  state = { hasError: false };
  static getDerivedStateFromError() {
    return { hasError: true };
  }
  handleRetry = () => this.setState({ hasError: false });
  render() {
    if (this.state.hasError) {
      return (
        <div>
          <p>Something went wrong</p>
          <button onClick={this.handleRetry}>Try Again</button>
        </div>
      );
    }
    return this.props.children;
  }
}
Real-world example A dashboard widget that occasionally fails due to a slow network request gives the user a Try Again button, letting them retry loading just that one widget instead of needing to refresh the entire page.

Common follow-ups: What happens if the same underlying problem causes the error again right after clicking retry?;How would you add a maximum number of retry attempts before showing a different message?