← Back to React, page 2

react-0040 · Hard senior

What is useOptimistic, how does it work with Actions, and what happens if the request fails?

useOptimistic lets you show the expected result of an async action immediately, while the real request is still running. It returns an optimistic copy of some state and a function to apply an update to it. The optimistic value exists only during the action. When the action finishes, React discards it and shows the real state, so a failed request automatically rolls the UI back.

Full answer

Waiting for a server before showing a sent message or a liked post makes interfaces feel slow. An optimistic update shows the likely result at once and reconciles later.

const [optimisticState, addOptimistic] = useOptimistic(state, updateFn) takes the real state and an optional reducer-like function, (currentState, optimisticValue) => newState. It returns the state to render and a setter to call. The setter must be called inside an Action, that is inside a form action or inside startTransition.

The flow is: the user submits, you call addOptimistic(value) straight away, and the UI renders the optimistic state. Then you await the request and update the real state when it succeeds. When the action completes, React stops using the optimistic value and renders whatever the real state now is. On success the real state already includes the item, so it appears to stay. On failure, the real state never changed, so the optimistic item disappears. This automatic rollback is the main benefit. Show an error message in the failure branch so the user knows why the item vanished.

Design notes. Mark optimistic items visually, for example "sending...", so the UI is honest. Use a temporary key or id and replace it with the server id on success. Do not use it for actions where being wrong is costly, such as payments, because showing success that later reverses is harmful. Use it for likes, comments, reordering and toggles.

The hook works together with the other React 19 form features: the form action calls addOptimistic, awaits the request, then updates the real list. Libraries such as TanStack Query have similar optimistic update helpers for data they manage.

In the example the server takes 150 milliseconds, but the message appears at once, flagged as sending.

jsx
import { useOptimistic, useState } from 'react';

function sendToServer(text) {
  return new Promise((resolve) => setTimeout(() => resolve({ id: Date.now(), text }), 150));
}

export default function Chat() {
  const [messages, setMessages] = useState([]);
  const [optimisticMessages, addOptimistic] = useOptimistic(messages, (current, text) => [
    ...current,
    { id: 'pending-' + text, text, sending: true },
  ]);

  async function send(formData) {
    const text = String(formData.get('text'));
    addOptimistic(text);
    const saved = await sendToServer(text);
    setMessages((current) => [...current, saved]);
  }

  return (
    <form action={send}>
      <input name="text" />
      <button type="submit">Send</button>
      <ul>
        {optimisticMessages.map((m) => (
          <li key={m.id}>
            {m.text}
            {m.sending ? ' (sending...)' : ''}
          </li>
        ))}
      </ul>
    </form>
  );
}

The check typed Hello and submitted the form. While the 150 millisecond request is running the list already shows the message with a sending label. After the answer, it appears as a normal message. Output of the run: while sending: Hello (sending...) after server answers: Hello

Key points

  • useOptimistic shows an expected state during an async action and reverts to real state afterwards.
  • Call the setter inside an Action (a form action or startTransition).
  • On failure the optimistic value disappears because real state never changed.
  • Mark optimistic items visibly and replace temporary ids when the server answers.
  • Avoid it for high-risk operations such as payments.

Common mistakes

  • Calling the optimistic setter outside an action or transition.
  • Forgetting to update real state, so the optimistic item vanishes when the action ends.
  • Using optimistic UI for irreversible or high-stakes operations.
  • Not showing an error, so users do not know why the item disappeared after a failure.
  • Reusing the temporary id as the final id.

Follow-ups

  • How would you add error handling and a retry message?
  • How does useOptimistic differ from setting state before the request and reverting in a catch block?
  • How would you handle two optimistic updates in flight at once?

Tips

  • Explain the rollback mechanism. It is the thing interviewers want to hear.
  • Mention honest UI (a pending marker) and the cases where you would not use it.
  • Link it to Actions and forms, since that is where it fits.