Instant mutation feedback
A user submits a form or mutation and the UI should reflect the expected result immediately.
React 19+ · Hook
useOptimistic lets a component display temporary optimistic state while an Action is pending. After the Action finishes or errors, React returns to the source value.
useOptimistic creates temporary UI state for an in-progress Action. React displays the optimistic value during the Action, then uses the source value again after the Action finishes or fails.
const [optimisticState, setOptimistic] = useOptimistic(value, reducer?)| Name | Type | Description |
|---|---|---|
value | any | The value used when no Action is pending and after the optimistic Action is complete. |
reducer | (currentState, action) => nextState | Optional pure function receiving the current optimistic state and an action, returning the next optimistic state. |
An array containing optimisticState and set. optimisticState is the value or reducer-derived temporary state; set updates it inside an Action.
import { useOptimistic, startTransition } from "react";
export default function LikeButton({ count }) {
const [optimisticCount, setOptimisticCount] = useOptimistic(count);
function handleClick() {
startTransition(async () => {
setOptimisticCount(optimisticCount + 1);
await saveLike();
});
}
return <button onClick={handleClick}>{optimisticCount} likes</button>;
}
async function saveLike() {
await new Promise(resolve => setTimeout(resolve, 500));
}The count changes immediately during the Action and returns to the source value when the Action completes.
A user submits a form or mutation and the UI should reflect the expected result immediately.
A network-backed control needs a temporary count, label, or status while its request is pending.
A list item should appear or change immediately while the server operation completes.
useOptimistic returns exactly two values: the current optimistic state and a setter. Without a pending Action, the state equals the value argument; during an Action, it reflects the reducer result or the setter value.
Follow-up: How should a reducer be designed? Keep it pure, accept the current state and action, and return the next optimistic state without side effects.
The first argument is the fallback value shown when no Action is pending. The optional reducer describes how an optimistic update transforms current state in response to an action.
Follow-up: What happens after the Action completes? React goes back to rendering the value supplied as the first argument.
The setter must run inside an Action, commonly inside startTransition. React then re-renders with the optimistic value while the asynchronous work is pending.
Follow-up: What if the setter runs outside an Action? React warns, and the optimistic state only renders briefly before the source value is used again.
startTransitionuseActionStateuseTransitionActions