useOptimistic

The React hook that shows a temporary optimistic value while an Action is pending, then returns to the real state when it settles.

In more detail

useOptimistic(state, updateFn) returns the value to display and a function to apply an optimistic change; call that function inside an Action or transition. If the Action fails, the optimistic value is simply dropped, so no manual rollback is needed.

Examples

const [likes, addLike] = useOptimistic(count, (c, n: number) => c + n);
const [optimisticLikes, addLike] = useOptimistic(likes, (cur, n) => cur + n);

Related terms

Taught in

References