Capítulo 60 de 116
useOptimistic(value, reducer?) shows a hoped-for result immediately while a real async Action is still in flight, then automatically reconciles back to the real value once the Action settles — the standard tool for "show the message as sent right away" UX.
const [optimisticState, setOptimistic] = useOptimistic(value, reducer?). value is the real, confirmed state (e.g. from props). optimisticState equals value whenever nothing is pending; while an Action is pending, it reflects the optimistic guess instead.reducer(currentState, action): like a useReducer reducer, computes the next optimistic state from an action payload — if omitted, calling the setter with a new value directly replaces the optimistic state.value itself updates to reflect the real result, optimisticState snaps back to just tracking value — there's no manual "clear the optimistic flag" step.useTransition/form action), not as a general "temporary override" mechanism disconnected from an actual async operation.value/UI accordingly, at which point the optimistic state reconciles to reflect that failure.function Thread({ messages, sendMessage }) {
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(state, newMessage) => [...state, { text: newMessage, sending: true }]
);
async function formAction(formData) {
addOptimisticMessage(formData.get('message'));
await sendMessage(formData.get('message')); // real Action; messages prop updates on success
}
return optimisticMessages.map(m => <p key={m.text}>{m.text}{m.sending && ' (sending...)'}</p>);
}
sendMessage Action confirms — optimisticMessages reconciles to the real messages prop once it does.value is automatic; on failure, the calling code must handle showing/reverting the error state itself.