Optimistic Update Pattern
How to update UI instantly and reconcile with the server in React: rollback on error, temp IDs, conflict handling, React 19 useOptimistic, and React Query.
Overview
A user clicks “like” and the heart fills instantly. The request hasn’t finished yet; the UI just decided to trust it will work. That’s an optimistic update: apply the change to local state immediately, send the request in the background, and reconcile afterwards. On success, the UI was already right. On failure, you restore the snapshot you took before mutating and show an error.
The result feels instant even on a slow network. The trade-off is that you now own three extra problems: rolling back cleanly, replacing temporary IDs, and deciding what happens when the server disagrees.
When to Use
- Like/unlike buttons, toggles, and other instant-feedback interactions
- Adding or removing items from a list (todo items, cart items)
- Inline edits (comments, titles, descriptions)
- Any action where the server almost always succeeds
- Apps where perceived speed matters more than momentary divergence
When NOT to Use
- Financial transactions: always wait for server confirmation
- Actions with high failure rates: rollback flicker degrades UX
- Operations that need server-side validation (unique name check)
- Multi-step workflows where later steps depend on earlier server state
- When the server is the source of truth and UI must reflect it exactly
Solution
Basic optimistic update with useState
// LikeButton.jsx — basic optimistic update
import React, { useState } from 'react';
function LikeButton({ postId, initialLiked, initialCount }) {
const [liked, setLiked] = useState(initialLiked);
const [count, setCount] = useState(initialCount);
const [error, setError] = useState(null);
const handleLike = async () => {
const previousLiked = liked;
const previousCount = count;
// Optimistic update — immediate UI change
setLiked(!liked);
setCount(prev => liked ? prev - 1 : prev + 1);
setError(null);
try {
const response = await fetch(`/api/posts/${postId}/like`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ liked: !liked }),
});
if (!response.ok) throw new Error('Failed to update like');
// Server confirmed — UI was already correct
} catch (err) {
// Rollback to previous state
setLiked(previousLiked);
setCount(previousCount);
setError('Could not update like. Please try again.');
}
};
return (
<div className="like-button">
<button onClick={handleLike} className={liked ? 'liked' : ''}>
{liked ? '♥' : '♡'} {count}
</button>
{error && <span className="error-text">{error}</span>}
</div>
);
}
export default LikeButton;
Optimistic list update with rollback
// TodoList.jsx — optimistic add and delete
import React, { useState } from 'react';
function TodoList({ initialTodos }) {
const [todos, setTodos] = useState(initialTodos);
const [error, setError] = useState(null);
const addTodo = async (text) => {
const tempId = crypto.randomUUID();
const newTodo = { id: tempId, text, completed: false, pending: true };
// Optimistic add
setTodos(prev => [...prev, newTodo]);
setError(null);
try {
const response = await fetch('/api/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text }),
});
const savedTodo = await response.json();
// Replace temp todo with server todo
setTodos(prev =>
prev.map(t => t.id === tempId ? { ...savedTodo, pending: false } : t)
);
} catch (err) {
// Rollback — remove the temp todo
setTodos(prev => prev.filter(t => t.id !== tempId));
setError('Failed to add todo. Please try again.');
}
};
const deleteTodo = async (id) => {
const previousTodos = todos;
// Optimistic delete
setTodos(prev => prev.filter(t => t.id !== id));
setError(null);
try {
const response = await fetch(`/api/todos/${id}`, { method: 'DELETE' });
if (!response.ok) throw new Error('Delete failed');
} catch (err) {
// Rollback
setTodos(previousTodos);
setError('Failed to delete. Please try again.');
}
};
const toggleTodo = async (id) => {
const todo = todos.find(t => t.id === id);
if (!todo) return;
// Optimistic toggle
setTodos(prev =>
prev.map(t => t.id === id ? { ...t, completed: !t.completed } : t)
);
try {
const response = await fetch(`/api/todos/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ completed: !todo.completed }),
});
if (!response.ok) throw new Error('Toggle failed');
} catch (err) {
// Rollback
setTodos(prev =>
prev.map(t => t.id === id ? { ...t, completed: todo.completed } : t)
);
setError('Failed to update. Please try again.');
}
};
return (
<div className="todo-list">
<form onSubmit={(e) => {
e.preventDefault();
const input = e.target.elements.text;
if (input.value.trim()) {
addTodo(input.value.trim());
input.value = '';
}
}}>
<input name="text" placeholder="New todo..." />
<button type="submit">Add</button>
</form>
{error && <div className="error">{error}</div>}
<ul>
{todos.map(todo => (
<li key={todo.id} className={todo.pending ? 'pending' : ''}>
<input
type="checkbox"
checked={todo.completed}
onChange={() => toggleTodo(todo.id)}
/>
<span style={{ textDecoration: todo.completed ? 'line-through' : '' }}>
{todo.text}
</span>
<button onClick={() => deleteTodo(todo.id)}>×</button>
</li>
))}
</ul>
</div>
);
}
export default TodoList;
React 19’s built-in useOptimistic
React 19 ships a native useOptimistic hook that handles the snapshot-and-rollback mechanics for you: inside a transition, you only describe what the optimistic state looks like. If you’re on React 19, prefer it over hand-rolled versions:
// OptimisticTodo.jsx — React 19 native useOptimistic
import React, { useState, useOptimistic, startTransition } from 'react';
function OptimisticTodo({ initialTodos }) {
const [todos, setTodos] = useState(initialTodos);
const [optimisticTodos, addOptimisticTodo] = useOptimistic(
todos,
(current, newTodo) => [...current, { ...newTodo, pending: true }]
);
const addTodo = (formData) => {
const text = formData.get('text');
const tempTodo = { id: crypto.randomUUID(), text, completed: false };
startTransition(async () => {
addOptimisticTodo(tempTodo); // shown instantly, rolls back if the action throws
const res = await fetch('/api/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text }),
});
if (!res.ok) throw new Error('Add failed');
const saved = await res.json();
setTodos(prev => [...prev, saved]); // commit the real state on success
});
};
return (
<form action={addTodo}>
<input name="text" placeholder="New todo..." />
<ul>
{optimisticTodos.map(t => (
<li key={t.id} style={{ opacity: t.pending ? 0.5 : 1 }}>{t.text}</li>
))}
</ul>
</form>
);
}
The mental difference: useOptimistic derives a temporary view from real state. When the transition ends, the optimistic overlay disappears and real state wins. You never write rollback code; React discards the overlay automatically if the action throws. The React 19 features guide covers useOptimistic together with Actions and useTransition.
React Query optimistic updates
// useOptimisticTodo.js — React Query with optimistic updates
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
function useTodos() {
const queryClient = useQueryClient();
const { data: todos = [] } = useQuery({
queryKey: ['todos'],
queryFn: () => fetch('/api/todos').then(res => res.json()),
});
const addTodoMutation = useMutation({
mutationFn: (text) =>
fetch('/api/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text }),
}).then(res => res.json()),
onMutate: async (text) => {
// Cancel outgoing refetches
await queryClient.cancelQueries({ queryKey: ['todos'] });
// Snapshot previous value
const previousTodos = queryClient.getQueryData(['todos']);
// Optimistically add
queryClient.setQueryData(['todos'], (old) => [
...old,
{ id: crypto.randomUUID(), text, completed: false, pending: true },
]);
// Return context with previous value
return { previousTodos };
},
onError: (err, text, context) => {
// Rollback on error
queryClient.setQueryData(['todos'], context.previousTodos);
},
onSettled: () => {
// Always refetch after error or success
queryClient.invalidateQueries({ queryKey: ['todos'] });
},
});
const deleteTodoMutation = useMutation({
mutationFn: (id) =>
fetch(`/api/todos/${id}`, { method: 'DELETE' }),
onMutate: async (id) => {
await queryClient.cancelQueries({ queryKey: ['todos'] });
const previousTodos = queryClient.getQueryData(['todos']);
queryClient.setQueryData(['todos'], (old) =>
old.filter((t) => t.id !== id)
);
return { previousTodos };
},
onError: (err, id, context) => {
queryClient.setQueryData(['todos'], context.previousTodos);
},
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ['todos'] });
},
});
const toggleTodoMutation = useMutation({
mutationFn: ({ id, completed }) =>
fetch(`/api/todos/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ completed }),
}),
onMutate: async ({ id, completed }) => {
await queryClient.cancelQueries({ queryKey: ['todos'] });
const previousTodos = queryClient.getQueryData(['todos']);
queryClient.setQueryData(['todos'], (old) =>
old.map((t) => t.id === id ? { ...t, completed } : t)
);
return { previousTodos };
},
onError: (err, variables, context) => {
queryClient.setQueryData(['todos'], context.previousTodos);
},
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ['todos'] });
},
});
return {
todos,
addTodo: addTodoMutation.mutate,
deleteTodo: deleteTodoMutation.mutate,
toggleTodo: toggleTodoMutation.mutate,
isAdding: addTodoMutation.isPending,
};
}
export default useTodos;
Generic optimistic state hook (pre-React 19)
On older React versions you can wrap the pattern in a small hook. It’s named useOptimisticState, not useOptimistic, which is taken by React 19’s built-in:
// useOptimisticState.js — generic optimistic update hook
import { useState, useCallback, useRef } from 'react';
function useOptimisticState(initialState) {
const [state, setState] = useState(initialState);
const [isOptimistic, setIsOptimistic] = useState(false);
const previousStateRef = useRef(initialState);
const optimisticUpdate = useCallback(
async (optimisticState, asyncFn) => {
previousStateRef.current = state;
// Apply optimistic state
setState(optimisticState);
setIsOptimistic(true);
try {
const result = await asyncFn();
// Server confirmed — keep the state, update with server data if provided
if (result !== undefined) {
setState(result);
}
setIsOptimistic(false);
return result;
} catch (error) {
// Rollback
setState(previousStateRef.current);
setIsOptimistic(false);
throw error;
}
},
[state]
);
return { state, setState, optimisticUpdate, isOptimistic };
}
export default useOptimisticState;
// Usage — draft stays local, optimistic update fires on save
function CommentEditor({ comment }) {
const { state: text, setState: setText, optimisticUpdate, isOptimistic } =
useOptimisticState(comment.text);
const handleSave = async () => {
try {
await optimisticUpdate(
text, // optimistic value, already shown in the textarea
() => fetch(`/api/comments/${comment.id}`, {
method: 'PATCH',
body: JSON.stringify({ text }),
}).then(res => res.json()).then(data => data.text)
);
} catch {
alert('Failed to save. Reverted to previous text.');
}
};
return (
<div>
<textarea value={text} onChange={(e) => setText(e.target.value)} />
<button onClick={handleSave} disabled={isOptimistic}>
{isOptimistic ? 'Saving...' : 'Save'}
</button>
</div>
);
}
Conflict resolution with versioning
// EditableTitle.jsx — handle concurrent edits
import React, { useState } from 'react';
function EditableTitle({ item }) {
const [title, setTitle] = useState(item.title);
const [version, setVersion] = useState(item.version);
const [conflict, setConflict] = useState(null);
const handleSave = async () => {
const previousTitle = title;
const previousVersion = version;
setConflict(null);
try {
const response = await fetch(`/api/items/${item.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title, version }),
});
if (response.status === 409) {
// Conflict — server has a newer version
const serverItem = await response.json();
setConflict({
serverTitle: serverItem.title,
yourTitle: title,
});
// Roll back to the server version
setTitle(serverItem.title);
setVersion(serverItem.version);
return;
}
const updated = await response.json();
setVersion(updated.version);
} catch (err) {
setTitle(previousTitle);
setVersion(previousVersion);
}
};
return (
<div>
<input value={title} onChange={(e) => setTitle(e.target.value)} />
<button onClick={handleSave}>Save</button>
{conflict && (
<div className="conflict-warning">
Another user edited this title to "{conflict.serverTitle}".
Your change "{conflict.yourTitle}" was reverted.
</div>
)}
</div>
);
}
Explanation
Every optimistic update is a short three-act play:
Three details make or break the implementation:
- The snapshot must be the pre-mutation state. If you capture state after applying the optimistic change, or capture a stale closure, your “rollback” restores the wrong thing. Snapshot first, then mutate.
- Temporary items need temporary IDs. The server will assign the real ID; your temp ID (
crypto.randomUUID()) exists only to key the row until the response arrives, when you swap temp for real. Never render a fake server ID; if a second action fires before the first resolves, you’ll update the wrong record. - The divergence window is real. Between the optimistic render and the response, UI and server disagree. Keep it short: if p95 latency for the endpoint is over ~2s, a spinner with a real request reads more honest than a fake success.
On conflicts (two users editing the same resource), send a version or etag with the write. A 409 means “someone got there first”: show their version and let the user decide, don’t silently overwrite.
Variants
Pessimistic fallback for critical operations
// MixedOptimistic.jsx — optimistic for low-risk, pessimistic for high-risk
function CartActions({ item }) {
const [quantity, setQuantity] = useState(item.quantity);
const updateQuantity = async (newQty) => {
if (newQty === 0) {
// Pessimistic — deleting from cart needs confirmation
const confirmed = window.confirm('Remove this item from cart?');
if (!confirmed) return;
await fetch(`/api/cart/${item.id}`, { method: 'DELETE' });
setQuantity(0);
} else {
// Optimistic — quantity change is low-risk
const prev = quantity;
setQuantity(newQty);
try {
await fetch(`/api/cart/${item.id}`, {
method: 'PATCH',
body: JSON.stringify({ quantity: newQty }),
});
} catch {
setQuantity(prev);
}
}
};
return (
<div>
<button onClick={() => updateQuantity(quantity - 1)}>-</button>
<span>{quantity}</span>
<button onClick={() => updateQuantity(quantity + 1)}>+</button>
</div>
);
}
Batch optimistic updates
// BatchOptimistic.jsx — multiple optimistic updates at once
function BulkComplete({ selectedIds, todos, setTodos }) {
const [error, setError] = useState(null);
const handleBulkComplete = async () => {
const previousTodos = [...todos];
// Optimistic: mark all selected as completed
setTodos(prev =>
prev.map(t =>
selectedIds.includes(t.id) ? { ...t, completed: true } : t
)
);
try {
await fetch('/api/todos/bulk-complete', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ids: selectedIds }),
});
} catch {
// Rollback all
setTodos(previousTodos);
setError('Failed to complete some items.');
}
};
return (
<button onClick={handleBulkComplete}>
Complete {selectedIds.length} items
</button>
);
}
Best Practices
- Snapshot before mutating: always capture the previous state so you can roll back
- Use temp IDs for new items:
crypto.randomUUID()until the server returns the real ID - Mark pending items visually: opacity, spinner, or a subtle indicator so users know it’s not confirmed
- Restore the exact previous state on error and show a message: silent rollbacks confuse users
- Keep the optimistic window short: if the server takes more than ~2 seconds, a loading state is more honest
- Handle conflicts: send a version and show the server’s copy on
409 - Prefer built-ins: React 19
useOptimisticor React Query’sonMutate/onError/onSettledover hand-rolled state - Don’t chain optimistic updates: wait for one to settle before starting the next
Common Mistakes
- No rollback: updating UI optimistically but not reverting on error. Users see stale data and don’t know the action failed.
- Using server IDs before they exist: assigning
id: 1optimistically when the server will assignid: 42. Use temp IDs and replace on success. - Chaining optimistic updates: updating the same item twice before the first request settles. The rollback of the first overwrites the second.
- Not handling 409 conflicts: two users edit the same resource. The server rejects one, but the UI never shows the conflict.
- Optimistic for everything: using optimistic updates for irreversible actions (delete account, process payment). Always wait for confirmation.
- Naming your hook
useOptimisticon React 19: the name is taken by the built-in, so imports collide and linters flag it. Call yours something else or migrate to the native hook.
See Also
- React docs:
useOptimistic: the React 19 built-in this pattern inspired - TanStack Query: Optimistic Updates: the canonical
onMutate/onError/onSettledrecipe - State Machine UI pattern: model the pending/confirmed/error states explicitly
- React 19 features guide:
useOptimisticin context with Actions and transitions
Companion code: optimistic update resources: the like button, the todo list, the React Query hook, the generic useOptimisticState hook, and the conflict-resolution component from this page.
Frequently Asked Questions
What is an optimistic update?
Changing the UI immediately when the user performs an action, without waiting for the server. If the request fails, the UI rolls back to a snapshot taken before the change. The app feels instant; you pay for it with rollback and reconciliation logic.
When should I avoid optimistic updates?
For irreversible actions (payments, deletions you can't undo), high-failure-rate operations, or anything the server must validate before the UI reflects it.
What's the difference between useOptimistic and a manual optimistic update?
React 19's useOptimistic derives a temporary view of your state inside a transition and drops it automatically when the action finishes. No rollback code. A manual implementation gives you the same result with explicit snapshots and error handling, and works on any React version.
How do I handle temp IDs?
Generate a temporary ID (e.g., crypto.randomUUID()) for the optimistic item. When the server responds with the real ID, replace the temp item with the server item so later actions target the real record.
Should I use React Query for optimistic updates?
If you're already using React Query, yes: onMutate gives you the snapshot point, onError the rollback, and onSettled the refetch for free. The state management guide compares it with other approaches.
Related Resources
Container-Presenter: Separate Data Logic from Rendering
How to separate data-fetching logic from rendering in React using the container-presenter pattern. Covers hooks migration, testing benefits, and trade-offs.
PatternCustom Hook Composition in React
How to compose reusable logic with custom React hooks. Covers hook composition, dependency arrays, context integration, memoization, and testing.
PatternSuspense Boundary: Declarative Loading States with React
How to use React Suspense boundaries for declarative loading states. Covers data fetching, streaming SSR, nested boundaries, and error boundaries.
PatternState Machine UI: Finite State Machines for UI
How to model UI state transitions with finite state machines in React. Covers XState, statecharts, guarded transitions, and preventing impossible states.
GuideComplete Guide to React 19 Features
A practical walkthrough of React 19: server components, the use() hook, actions, ref as a prop, document metadata, asset loading, and the React Compiler.
GuideReact State Management: Zustand, Jotai, TanStack Query
How to choose and combine React state management tools: Context API, Zustand, Jotai, and TanStack Query for server state, with patterns and a decision framework.