DEV Community

Discussion on: Optimizing React Components with Error Boundaries

Collapse
 
dance2die profile image
Sung M. Kim

Thanks for the post, Johnson. Your post is a good based on the official doc~

One thing I'd like to mention is that, when an error boundary catches and error, it normally shows a "fallback UI".

 class ErrorBoundary extends Component {
    // ... rest removed for brevity

    render() {
      if (this.state.hasError) {
        // 👇 here shows the fallback UI
        return <h1>Something went wrong.</h1>;
      }

      return this.props.children; 
    }
 }

But once it shows the fallback, there isn't a documentation on how to "clear" the error boundary (if it's a non-critical error as an example).

I asked for a feature for react-error-boundary (by Brian Vaughn of React core team) to enable "clearing the boundary".

It's basically a bit more mature version of what's in the documentation.

And his response was to add a "key" to the Error Boundary component and change the key to re-render the children.

github.com/bvaughn/react-error-bou...

class App extends React.Component {
  state = {
    errorBoundaryKey: 0
  };

  handleRerenderButtonClick = () => this.forceUpdate();

  handleResetButtonClick = () =>
    this.setState(prevState => ({
      errorBoundaryKey: prevState.errorBoundaryKey + 1
    }));

  render() {
    return (
      <div className="App">
        <button onClick={this.handleRerenderButtonClick}>re-render</button>
        <button onClick={this.handleResetButtonClick}>
          reset error boundary
        </button>
        {/*           ... 👇 ... */}
        <ErrorBoundary key={this.state.errorBoundaryKey}>
          <ComponentThatMayError />
        </ErrorBoundary>
      </div>
    );
  }
}
Collapse
 
ogwurujohnson profile image
Johnson Ogwuru

wow, makes sense, Thanks for sharing this Sung