Optimistic UI & Mutation Concurrency
Optimistic UI shows the expected result before the server confirms it.
user intent
β
optimistic state immediately
β
server mutation
β
confirmed server state or failure recovery
React's useOptimistic supports this pattern inside Actions.
Basic useOptimisticβ
'use client'
import { useOptimistic } from 'react'
import { sendMessage } from './actions'
export function Thread({
messages,
}: {
messages: Message[]
}) {
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(state, text: string) => [
...state,
{ id: `optimistic-${Date.now()}`, text, pending: true },
],
)
async function formAction(formData: FormData) {
const text = String(formData.get('message') ?? '')
addOptimisticMessage(text)
await sendMessage(text)
}
return (
<>
{optimisticMessages.map((message) => (
<p key={message.id}>{message.text}</p>
))}
<form action={formAction}>
<input name="message" />
<button>Send</button>
</form>
</>
)
}
The optimistic reducer should be pure.
Optimistic state is a projection, not authorityβ
Never treat optimistic state as proof that the mutation succeeded.
optimistic UI
= predicted presentation
server/database
= authoritative state
This distinction matters for:
- payments
- inventory
- permissions
- uniqueness
- collaboration
- quotas
Good candidatesβ
Optimistic UI is strongest when:
high expected success rate
low rollback cost
clear user intent
fast reconciliation
Examples:
- likes
- toggles
- reordering
- adding a comment
- marking a task complete
Weak candidatesβ
Be cautious with:
- irreversible payments
- destructive deletes
- permission grants
- legal confirmations
- inventory-sensitive checkout
- operations with frequent business-rule rejection
You can still provide pending feedback without pretending success.
The server may normalize the resultβ
Client prediction:
name = " New Project "
Server result:
name = "New Project"
slug = "new-project"
updatedAt = server timestamp
Optimistic UI must reconcile to authoritative returned/rendered data.
Failure recoveryβ
If the action fails, React's optimistic state should resolve back toward the base state after the Action ends.
But UX still needs to explain failure.
Pattern:
optimistic visual change
β
server rejects
β
optimistic projection disappears
β
show useful error
Do not silently snap back without context for meaningful operations.
Temporary IDsβ
For optimistic creation, the client may need a temporary identifier.
const optimisticId = crypto.randomUUID()
But the database may create a different authoritative ID.
Model reconciliation explicitly:
client temp ID
β
server create
β
real ID
β
new server render/result replaces optimistic item
Do not persist assumptions about the temporary ID.
Multiple optimistic updatesβ
Suppose the user clicks βLikeβ three times quickly or toggles a state repeatedly.
You now have ordering questions:
intent A
intent B
intent C
Are these:
- additive operations?
- replacements?
- toggles?
- cancellable?
Design the server contract accordingly.
Prefer intent-based mutationsβ
For concurrency-sensitive operations, this may be safer:
incrementQuantity(itemId, 1)
than:
setQuantity(itemId, clientQuantity)
But for some domains, absolute state with version checks is safer.
The correct choice depends on conflict semantics.
Lost updatesβ
Classic race:
Client A reads version 4
Client B reads version 4
A writes version 5
B writes based on version 4
Possible solutions:
- optimistic concurrency version columns
- conditional updates
- database transactions
- row locking
- merge rules
- event sourcing for suitable domains
React optimistic UI does not solve database concurrency.
Version-aware mutationβ
await db.document.updateMany({
where: {
id,
version: expectedVersion,
},
data: {
body,
version: { increment: 1 },
},
})
If zero rows update, return a conflict state.
The UI can then:
- refetch/re-render
- show conflict
- offer merge/retry
Optimistic deleteβ
Removing an item immediately can feel fast.
But if delete fails, restoring the exact prior position/state may be awkward.
For high-risk deletes, consider:
pending deletion state
β server confirms
β remove permanently
instead of immediate disappearance.
Combine with useActionStateβ
Optimistic presentation and action result state solve different problems.
useOptimistic
β predicted UI
useActionState
β returned result/error + pending
They can work together.
Revalidation after optimistic mutationβ
After the server commits, invalidate/refresh the authoritative server data so the next render confirms:
optimistic projection
β
write
β
updateTag / revalidateTag / revalidatePath / refresh as appropriate
β
server render
β
confirmed state
Do not maintain two permanent competing sources of truth.
Read-your-own-writesβ
For cached data where the user must see their own write immediately, updateTag can expire the relevant tag inside a Server Action.
Use this when immediate consistency is the product requirement.
If slight staleness is acceptable, revalidateTag(tag, 'max') may be more appropriate.
Pending vs optimisticβ
Pending UI:
Save β Savingβ¦
Optimistic UI:
Save β UI already shows new value
Use optimistic state only when the product benefits from prediction.
Duplicate clicksβ
Optimistic UI can make duplicate clicks more dangerous because the interface appears fast.
Still design:
- disabled/pending states where useful
- idempotency
- unique constraints
- state-machine transitions
Queued Actionsβ
React Action state may queue mutations that depend on previous state.
Do not assume client invocation order equals arbitrary distributed transaction ordering across tabs/devices/services.
Server-side invariants remain authoritative.
Collaborationβ
In multi-user systems:
my optimistic edit
+
remote user's edit
+
server reconciliation
can conflict.
Define:
- last-write-wins?
- field merge?
- explicit conflict?
- CRDT/OT for collaborative editing?
Optimistic UI is presentation; collaboration strategy is domain architecture.
Common mistakesβ
Using optimistic UI for every mutationβ
Prediction has product and correctness costs.
Treating optimistic state as successβ
Wait for authoritative confirmation.
No visible rollback errorβ
Users need to know why state reverted.
Ignoring server normalizationβ
Always reconcile with the actual result.
Assuming React solves concurrent writesβ
Database/domain concurrency needs its own mechanism.
Debugging checklistβ
- Slow the network deliberately.
- Force server rejection.
- Submit twice rapidly.
- Test two browser tabs.
- Test stale version conflict.
- Inspect optimistic temporary IDs.
- Confirm authoritative server data replaces prediction.
- Confirm revalidation is scoped correctly.
- Confirm pending and optimistic indicators are understandable.
- Test screen-reader feedback for failure/recovery.
Interview questionsβ
What does useOptimistic solve?
Immediate predicted UI during an Action while the authoritative mutation completes.
Does optimistic UI remove the need for pending state?
No. Pending state can still communicate that confirmation is in progress.
How do you handle concurrent updates?
With domain/database strategies such as version checks, conditional writes, transactions, or merge rules; optimistic UI alone is not concurrency control.
When should you avoid optimistic UI?
When failure is common, rollback is confusing, or the operation is high-risk and should not appear successful before confirmation.
Exerciseβ
Design optimistic UX for:
like post
rename task
reorder cards
delete customer
submit payment
For each, decide:
- optimistic or pending-only
- rollback UX
- server concurrency strategy
- revalidation strategy
- idempotency requirement