Optimistic UI with useOptimistic
Optimistic UI shows the user an expected result before the underlying Action has finished.
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β
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.
Automatic rollback does not automatically explain the failure. Important operations still need understandable error and retry UX.
Use a reducer for related optimistic updatesβ
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.
add item Β· follow Β· mark pending deletePrefer 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β
Avoid unexplained βsnap backβ behaviour for meaningful operations.
Loading vs optimistic stateβ
You can use both: show the optimistic item immediately while marking it as pending.
useOptimistic + useActionStateβ
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β
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β
- https://react.dev/reference/react/useOptimistic
- https://react.dev/reference/react/useActionState
- https://react.dev/reference/react/useTransition
Nextβ
Continue with use and Suspense Resources.