CodePark/ questions / Concurrent & React 19
START PRACTICINGPRACTICE
Frontend question · React › Concurrent & React 19

What does useOptimistic do? Describe how it behaves when the request succeeds and when it fails.

const [optimisticMessages, addOptimistic] = useOptimistic(
  messages,
  (current, text) => [...current, { text, sending: true }]
);

async function send(formData) {
  addOptimistic(formData.get('text'));
  await sendMessage(formData);
}

useOptimistic shows a temporary value while an async Action runs. On success, the real state takes over with the confirmed data. On failure, the temporary value simply disappears.

An Action is an async function that React runs as a non-urgent update and tracks until it finishes. useOptimistic(state, updateFn) returns [optimisticState, addOptimistic]. Call addOptimistic(input) inside an Action or a transition. React immediately renders updateFn(currentState, input). For example, it shows a new chat message marked as sending.

The optimistic value only lives while the Action is pending. When it finishes, React switches back to the real state you passed in:

  • On success, you will have updated that state with the server's result. So the UI shows the confirmed data.
  • On failure, the real state never changed. So the optimistic item disappears, and you can show an error.

This makes likes, comments or chat feel instant. You don't need to track and roll back temporary state by hand.

  • useOptimistic returns [optimisticState, addOptimistic].
  • Call addOptimistic inside an Action or a transition.
  • The optimistic value shows only while the Action is pending.
  • Afterwards React returns to the real state: confirmed on success, reverted on failure.
  • It removes manual rollback logic.