Part 13 / Topic 3 of 5
Reset patterns
A boundary's own resetBoundary() only ever forgets its own error state - it does nothing about whatever actually caused the throw. Section 2's retry button proved that the hard way. examples/03_reset_pattern_retry_and_key_remount.jsx covers the three patterns that actually work, each solving a different shape of "when should this stop showing the old error":
Pattern 1 - fix the cause, then reset. The retry button does the data fix first, and only calls reset() once there is actually something that will not throw again:
// examples/03_reset_pattern_retry_and_key_remount.jsx
function retryWithFreshStatus(reset) {
setOrder({ id: "ZO-4471", status: "out for delivery" });
reset();
}
Clicking it really recovers, with the order's real text back on screen (examples/03_reset_pattern_retry_and_key_remount.test.jsx) - the difference from Section 2 is only that order change, not the reset call.
Pattern 2 - resetKeys: reset itself when what it's watching changes, no button at all. A boundary that tracks a resetKeys array compares it on every update and resets the instant an entry changes:
// examples/03_reset_pattern_retry_and_key_remount.jsx
componentDidUpdate(prevProps) {
if (this.state.error && prevProps.resetKeys?.some((key, i) => key !== this.props.resetKeys[i])) {
this.setState({ error: null });
}
}
<ErrorBoundary resetKeys={[order.id]} fallback={(error) => <p role="alert">...</p>}>
<LiveOrderWidget order={order} />
</ErrorBoundary>
Clicking "Next order" really clears a cancelled order's fallback and shows the next order normally, with nothing inside the boundary clicked at all (examples/03_reset_pattern_retry_and_key_remount.test.jsx) - this is the right shape whenever "the user picked something else" is reason enough to drop an old error, which is most of the time a list/detail view changes its selection.
Pattern 3 - remount with key. Changing an element's key tells React this is a brand-new element, not an update to the old one - the crashed instance (and the boundary's own state right along with it) is thrown away and a fresh tree mounts from scratch:
// examples/03_reset_pattern_retry_and_key_remount.jsx
<ErrorBoundary key={attempt} fallback={(error) => <p role="alert">...</p>}>
<LiveOrderWidget order={order} />
</ErrorBoundary>
This is the bluntest option, correct specifically when there is no narrower state worth preserving across the reset and "start this part of the screen over completely" is actually what should happen.
Done here? The practice set for Part 13 — including the solutions — is on the part page.