Make "optimistic" declarative
useOptimistic lets you show the expected outcome of an action before the server confirms. The hook gives you a temporary "pretend" state that reverts automatically if the action fails.
Shape
const [optimistic, addOptimistic] = useOptimistic(realState, reducer). Call addOptimistic with the change, then run the action. The optimistic state holds until the action resolves and the cache revalidates.
Patterns where it pays
- Likes, hearts, favorites — immediate feedback feels essential.
- Toggles where the round-trip is >100ms.
- Adding items to a list (with a sending… indicator).
Define an identity and reconciliation rule for every optimistic item. A temporary list entry needs a temporary key, a visible sending state, and a deterministic replacement when the server returns the real record. Failures need a retry or undo path.
Immediate feedback is not the same as pretending every operation succeeded. Payments and permission changes should react immediately with progress, but confirmation must wait for the server. Optimism is appropriate when rollback is natural and the predicted result is unambiguous. Throttle the network and exercise success, failure, and rapid repeated input. Watch ordering, duplicate IDs, rollback, and cache revalidation. The UI should never briefly claim a durable result that the product cannot safely retract.