React › Error Boundaries
How would you build a reusable error boundary that lets the user retry after an error occurs?
AdvancedAnswer
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.