useOptimistic

Shows an optimistic state while an async action is in progress.

Since React 19 Spec ↗

Syntax

const [optimistic, addOptimistic] = useOptimistic(state, updateFn)

Parameters

NameTypeRequiredDescription
state any Yes The actual state returned when no action is pending.
updateFn function Yes Pure function (currentState, optimisticValue) returning the merged optimistic state.

Returns

array — A pair: the optimistic state and a function to apply an optimistic update.

Examples

function Thread({ messages, sendMessage }) {
  const [optimistic, addOptimistic] = useOptimistic(
    messages,
    (state, text) => [...state, { text, sending: true }]
  );

  async function action(formData) {
    const text = formData.get('message');
    addOptimistic(text);
    await sendMessage(text);
  }
  return <form action={action}>...</form>;
}

Notes

The optimistic value is shown immediately and automatically reverts to the real state once the action settles and the component re-renders. Call addOptimistic inside an action or transition. The update function must be pure.

See also