Skip to main content

Optimistic UI with useOptimistic

Optimistic UI shows the user an expected result before the underlying Action has finished.

Optimistic mutation lifecycleThe UI temporarily projects the expected result while canonical state is still being confirmed.
1User intent
2Optimistic projection appears
3Action remains pending
4Canonical result arrives
5Projection converges or rolls back

React provides useOptimistic for this pattern:

const [optimisticState, setOptimistic] = useOptimistic(value);

Or with a reducer:

const [optimisticState, dispatchOptimistic] = useOptimistic(
value,
reducer,
);

Optimistic state is temporary​

Canonical state remains the source of truth
Canonical value
Props/state/cache value that actually owns the data.
Optimistic projection
Temporary expected UI layered on top of the canonical value.
Canonical value renders again
Success catches up; failure naturally removes the projection.

useOptimistic does not replace the source of truth.

Basic example​

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

function LikeButton() {
const [liked, setLiked] = useState(false);
const [optimisticLiked, setOptimisticLiked] = useOptimistic(liked);

function handleClick() {
const nextLiked = !optimisticLiked;

startTransition(async () => {
setOptimisticLiked(nextLiked);

const saved = await saveLike(nextLiked);

startTransition(() => {
setLiked(saved.liked);
});
});
}

return (
<button onClick={handleClick}>
{optimisticLiked ? 'β™₯ Liked' : 'β™‘ Like'}
</button>
);
}

The user sees immediate feedback while the canonical liked state waits for confirmation.

Optimistic updates belong inside an Action​

Incorrect:

setOptimisticLiked(true); // 🚩 outside Action/Transition

Use:

startTransition(() => {
setOptimisticLiked(true);
});

A function-valued Action prop also provides Action context.

Why rollback can happen automatically​

Suppose canonical liked is still false, while the optimistic projection temporarily shows true.

Success vs failure convergence
Success
Canonical state changes to the optimistic result, so the projection and source agree.
Failure
Canonical state stays unchanged, so the temporary projection disappears when the Action ends.

Automatic rollback does not automatically explain the failure. Important operations still need understandable error and retry UX.

A reducer helps one intent update several related values consistently:

function optimisticReducer(state, action) {
switch (action.type) {
case 'follow':
return {
...state,
following: true,
followerCount: state.followerCount + 1,
};
case 'unfollow':
return {
...state,
following: false,
followerCount: state.followerCount - 1,
};
default:
return state;
}
}

const [optimisticUser, dispatchOptimistic] = useOptimistic(
user,
optimisticReducer,
);

The reducer should remain pure and immutable.

Why intent-based reducers matter​

Canonical data may change from somewhere else while an optimistic Action is still pending.

Project intent onto the latest base
Latest canonical base
Optimistic reducer
add item Β· follow Β· mark pending delete
Current optimistic projection

Prefer representing intent over copying an entire stale next-state snapshot.

Better:

{type: 'add', item: newItem}

Less robust:

{entireNextArray: staleArray}

Optimistic list insertion​

function TodoList({todos, addTodoAction}) {
const [optimisticTodos, addOptimisticTodo] = useOptimistic(
todos,
(currentTodos, newTodo) => [
...currentTodos,
{...newTodo, pending: true},
],
);

function handleAdd(text) {
const optimisticTodo = {
id: crypto.randomUUID(),
text,
};

startTransition(async () => {
addOptimisticTodo(optimisticTodo);
await addTodoAction(optimisticTodo);
});
}

return (
<ul>
{optimisticTodos.map(todo => (
<li key={todo.id}>
{todo.text}
{todo.pending && ' (Adding…)'}
</li>
))}
</ul>
);
}

Stable temporary identity matters for keys, focus, editing, pending styling, and reconciling the confirmed item.

Optimistic delete needs recovery design​

Removing an item immediately may hide the information required for retry. A safer design can mark it as pending deletion:

function reducer(items, action) {
switch (action.type) {
case 'delete':
return items.map(item =>
item.id === action.id
? {...item, pendingDelete: true}
: item,
);
default:
return items;
}
}

The UI can fade or disable the item while keeping enough context for recovery.

Failure UX​

Failure should be visible, not mysterious
1Show optimistic result
2Request fails
3Canonical state remains unchanged
4Projection disappears
5Explain error + offer recovery

Avoid unexplained β€œsnap back” behaviour for meaningful operations.

Loading vs optimistic state​

Two different UX statements
Pending/loading
β€œI am waiting for confirmation.”
Optimistic
β€œI expect this result, so I will show it while confirmation happens.”

You can use both: show the optimistic item immediately while marking it as pending.

useOptimistic + useActionState​

Complementary Action primitives
useActionState
Confirmed Action result + pending lifecycle + ordered result state.
useOptimistic
Immediate temporary projection.
Canonical state replaces projection
const [cart, cartAction, isPending] = useActionState(saveCart, initialCart);
const [optimisticCart, updateOptimisticCart] = useOptimistic(cart, cartReducer);

When optimistic UI fits​

Good candidates often include likes/reactions, follows, lightweight item creation, preference toggles, and low-risk ordering changes with a high success rate and clear rollback.

Higher-risk operations need caution: payments, irreversible destructive actions, security-sensitive permission changes, inventory reservation, or any flow where showing success before confirmation would be misleading or dangerous.

Do not mutate canonical state​

Bad:

function optimisticReducer(items, newItem) {
items.push(newItem); // ❌
return items;
}

Good:

function optimisticReducer(items, newItem) {
return [...items, newItem];
}

Production decision guide​

Should this mutation use optimistic UI?
Must wait for confirmation before showing success?Use pending/loading UI
Expected result unsafe or misleading to show early?Do not use optimistic UI
Result can be reconciled or rolled back cleanly?useOptimistic may fit
Canonical data may change while pending?Prefer reducer-based optimistic intent
Failure needs explicit recovery?Keep enough optimistic metadata for retry/error UX

Common mistakes​

  • Treating optimistic state as permanent/canonical state.
  • Calling the optimistic setter outside an Action/Transition.
  • Showing premature success for high-risk operations.
  • Providing no failure feedback.
  • Using unstable keys for temporary items.
  • Copying stale base state instead of applying intent.
  • Mutating the canonical collection in the optimistic reducer.

Interview questions​

Junior: What happens to optimistic state after the Action completes?

Mid-level: Why can a reducer be safer than passing a complete optimistic value when base state may change?

Senior: Which product operations should not use optimistic UI, and how would you design failure recovery for optimistic list mutations?

References​

Next​

Continue with use and Suspense Resources.