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

State Management in Error Boundaries

Tracking hasError state to conditionally render fallback UI, and resetting state to recover from errors.

State Management in Error Boundaries

You'll learn how to track error state inside an Error Boundary to conditionally show fallback UI and reset back to normal after recovery.

The Core Pattern: hasError State

Error Boundaries rely on internal state to track whether an error has occurred. When getDerivedStateFromError is called, you update state to mark the error condition:

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state to trigger fallback UI
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    console.error('Error caught:', error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // Conditionally render fallback
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children;
  }
}

Resetting State to Recover

The hasError flag controls the UI, so to recover from an error, you simply reset it to false:

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

render() {
  if (this.state.hasError) {
    return (
      <div>
        <h1>Something went wrong.</h1>
        <button onClick={this.resetError}>Try Again</button>
      </div>
    );
  }

  return this.props.children;
}

Clicking "Try Again" clears the error state and re-renders the children—giving them a chance to load successfully.

Think of It Like a Circuit Breaker

When an error "trips" the boundary, hasError flips to true like a circuit breaker cutting power. The reset method "flips the switch back," restoring normal operation.

Key Takeaway: Error Boundary state management revolves around a hasError boolean—set to true by getDerivedStateFromError to show fallback UI, and reset to false manually to recover and retry rendering children.