Course contentsShow
← React
Lesson 1305 of 2,39633. Error BoundariesFree lesson

Resetting Error Boundaries

Implementing reset functionality with key props or explicit reset methods to recover from error states.

Resetting Error Boundaries

You'll learn how to give users a way to recover from errors by resetting the error boundary back to a normal state.

Once an error boundary catches an error, it renders its fallback UI—but it stays in that error state forever. Users are stuck looking at the error screen unless they refresh the entire page. That's a poor experience. Resetting means clearing the error state so the component tree can try rendering again.

Two Common Reset Strategies

1. The Key Prop Reset Pattern

The simplest approach: wrap your error boundary in a parent component that can change its key prop. When the key changes, React unmounts and remounts the entire boundary, clearing its internal error state:

function App() {
  const [resetKey, setResetKey] = useState(0);

  return (
    <ErrorBoundary key={resetKey}>
      <button onClick={() => setResetKey(k => k + 1)}>
        Try Again
      </button>
      <ProblematicComponent />
    </ErrorBoundary>
  );
}

When you increment resetKey, the error boundary gets a fresh start.

2. Explicit Reset Method

Pass a reset function as a prop to your error boundary's fallback UI:

class ErrorBoundary extends Component {
  state = { hasError: false };

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

  resetError = () => {
    this.setState({ hasError: false });
  };

  render() {
    if (this.state.hasError) {
      return this.props.fallback({ reset: this.resetError });
    }
    return this.props.children;
  }
}

// Usage:
<ErrorBoundary fallback={({ reset }) => (
  <button onClick={reset}>Try Again</button>
)}>

The key pattern is simpler; the explicit method gives you more control over when and how resets happen.

Key Takeaway: Error boundaries need reset mechanisms—either through key prop changes or explicit reset methods—so users can attempt recovery without a full page reload.