JavaScript and React course Β· Module 9: Modern React Hooks
useOptimistic - optimistic UI updates
In this lesson4
A message to the Mars base takes several minutes to arrive, but the crew does not want to stare at a spinner. They want to see their message on the list right away, marked "sending". If the transmission fails, the message should disappear. That is an optimistic update: we assume success, and on failure we go back to the real state.
The useOptimistic hook allows you to instantly update the user interface before receiving a response from the server. This is a key tool for creating responsive applications that give the user the impression of instantaneous reaction.
useOptimistic Basics
1. Syntax and basic usage
The hook takes the real state and an update function, and returns the optimistic state plus a function that changes it. The most important rule from react.dev: that function must be called inside an Action, meaning in startTransition or in a form action. Outside an Action, React prints a warning and the change flashes and disappears at once. First, the task list logic:
import { useOptimistic, useState, startTransition } from 'react';
function TodoList() {
const [todos, setTodos] = useState([
{ id: 1, text: 'Learn React', completed: false },
{ id: 2, text: 'Build an app', completed: false }
]);
const [optimisticTodos, addOptimisticTodo] = useOptimistic(
todos,
// Function updating optimistic state
(currentTodos, newTodo) => [...currentTodos, newTodo]
);
async function handleAddTodo(text) {
const newTodo = {
id: Date.now(),
text,
completed: false,
pending: true // Mark as pending
};
// Optimistic update
addOptimisticTodo(newTodo);
try {
// Actual API call
const response = await fetch('/api/todos', {
method: 'POST',
body: JSON.stringify({ text })
});
const savedTodo = await response.json();
// Update actual state
startTransition(() => {
setTodos(current => [...current, savedTodo]);
});
} catch (error) {
// On error, optimistic state will be automatically rolled back
console.error('Error adding todo:', error);
}
}
The optimistic task exists only while the Action is running. When it ends, React shows the plain todos state. If saving succeeded, setTodos has already added the real task, and if it failed, the state is what it was before, so the change "rolls back" on its own. We wrap the update after await in another startTransition, as the examples in the docs do. Here is the view:
return (
<div style={{ maxWidth: '500px', margin: '0 auto', padding: '20px' }}>
<h2>Task List</h2>
<form
onSubmit={(e) => {
e.preventDefault();
const text = e.target.todo.value;
if (text) {
startTransition(() => handleAddTodo(text));
e.target.reset();
}
}}
style={{ marginBottom: '20px' }}
>
<input
name="todo"
style={{
width: '70%',
padding: '8px',
marginRight: '10px',
border: '1px solid #ddd',
borderRadius: '4px'
}}
/>
<button
type="submit"
style={{
padding: '8px 16px',
backgroundColor: '#007bff',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
>
Add
</button>
</form>
<ul style={{ listStyle: 'none', padding: 0 }}>
{optimisticTodos.map(todo => (
<li
key={todo.id}
style={{
padding: '10px',
marginBottom: '5px',
backgroundColor: todo.pending ? '#f0f8ff' : '#f8f9fa',
border: '1px solid #ddd',
borderRadius: '4px',
opacity: todo.pending ? 0.7 : 1,
transition: 'all 0.3s'
}}
>
<input
type="checkbox"
checked={todo.completed}
readOnly
style={{ marginRight: '10px' }}
/>
<span style={{
textDecoration: todo.completed ? 'line-through' : 'none'
}}>
{todo.text}
</span>
{todo.pending && (
<span style={{
marginLeft: '10px',
color: '#007bff',
fontSize: '12px'
}}>
(saving...)
</span>
)}
</li>
))}
</ul>
</div>
);
}The form calls handleAddTodo inside startTransition, so the optimistic entry marked "(saving...)" stays on screen until the server responds.
2. Optimistic toggle with error handling
A like button is the classic case: the reaction must be instant, and the server confirms it in the background. Here the update function simply returns the new value:
import { useOptimistic, useState, startTransition } from 'react';
function LikeButton({ postId, initialLikes, initialIsLiked }) {
const [likes, setLikes] = useState(initialLikes);
const [isLiked, setIsLiked] = useState(initialIsLiked);
const [optimisticLikes, updateOptimisticLikes] = useOptimistic(
{ count: likes, isLiked },
(current, optimisticValue) => optimisticValue
);
async function handleLikeToggle() {
const newIsLiked = !optimisticLikes.isLiked;
const newCount = optimisticLikes.count + (newIsLiked ? 1 : -1);
// Optimistic update
updateOptimisticLikes({
count: newCount,
isLiked: newIsLiked
});
try {
const response = await fetch(`/api/posts/${postId}/like`, {
method: newIsLiked ? 'POST' : 'DELETE'
});
if (!response.ok) {
throw new Error('Update error');
}
const data = await response.json();
// Update actual state
setLikes(data.likes);
setIsLiked(data.isLiked);
} catch (error) {
// Optimistic state will be automatically rolled back
alert('Failed to update like');
}
}
return (
<button
onClick={() => startTransition(handleLikeToggle)}
style={{
display: 'flex',
alignItems: 'center',
gap: '8px',
padding: '8px 16px',
backgroundColor: optimisticLikes.isLiked ? '#dc3545' : '#fff',
color: optimisticLikes.isLiked ? '#fff' : '#dc3545',
border: '1px solid #dc3545',
borderRadius: '20px',
cursor: 'pointer',
transition: 'all 0.3s',
fontSize: '16px'
}}
>
<span>{optimisticLikes.isLiked ? 'Liked' : 'Like'}</span>
<span>{optimisticLikes.count}</span>
</button>
);
}
// Example usage in a post component
function Post({ post }) {
return (
<article style={{
padding: '20px',
marginBottom: '20px',
backgroundColor: '#fff',
borderRadius: '8px',
boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
}}>
<h3>{post.title}</h3>
<p>{post.content}</p>
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginTop: '15px'
}}>
<LikeButton
postId={post.id}
initialLikes={post.likes}
initialIsLiked={post.isLiked}
/>
<span style={{ color: '#6c757d', fontSize: '14px' }}>
{new Date(post.createdAt).toLocaleDateString('en-US')}
</span>
</div>
</article>
);
}A click runs handleLikeToggle inside startTransition. When the server returns an error, the catch block shows a message, and the counter goes back to the value from likes, because the real state did not change.
3. Optimistic sorting and filtering
The update function works like a reducer: it receives the current state and a description of the change. That way one call handles both the checkbox and the priority change:
import { useOptimistic, useState, startTransition } from 'react';
function OptimisticTaskList() {
const [tasks, setTasks] = useState([
{ id: 1, title: 'Task 1', priority: 'low', completed: false },
{ id: 2, title: 'Task 2', priority: 'high', completed: false },
{ id: 3, title: 'Task 3', priority: 'medium', completed: true }
]);
const [optimisticTasks, updateOptimisticTask] = useOptimistic(
tasks,
(currentTasks, { id, updates }) =>
currentTasks.map(task =>
task.id === id ? { ...task, ...updates, updating: true } : task
)
);
async function handleTaskUpdate(taskId, updates) {
// Optimistic update
updateOptimisticTask({ id: taskId, updates });
try {
const response = await fetch(`/api/tasks/${taskId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(updates)
});
const updatedTask = await response.json();
// Update actual state
setTasks(current =>
current.map(task => task.id === taskId ? updatedTask : task)
);
} catch (error) {
console.error('Error updating task:', error);
}
}
const priorityColors = {
low: '#28a745',
medium: '#ffc107',
high: '#dc3545'
};
React runs this function again if the real tasks changes during the Action, so the change is always applied on top of current data. Here is the view with statistics:
return (
<div style={{ maxWidth: '600px', margin: '0 auto', padding: '20px' }}>
<h2>Task Management</h2>
<div style={{ marginBottom: '20px' }}>
<h3>Statistics:</h3>
<div style={{ display: 'flex', gap: '20px', fontSize: '14px' }}>
<span>
Completed: {optimisticTasks.filter(t => t.completed).length}
</span>
<span>
In progress: {optimisticTasks.filter(t => !t.completed).length}
</span>
<span>
High priority: {optimisticTasks.filter(t => t.priority === 'high').length}
</span>
</div>
</div>
<div style={{ display: 'grid', gap: '10px' }}>
{optimisticTasks.map(task => (
<div
key={task.id}
style={{
padding: '15px',
backgroundColor: task.updating ? '#f0f8ff' : '#fff',
border: '1px solid #ddd',
borderRadius: '8px',
opacity: task.updating ? 0.8 : 1,
transition: 'all 0.3s'
}}
>
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center'
}}>
<div style={{ flex: 1 }}>
<input
type="checkbox"
checked={task.completed}
onChange={(e) =>
startTransition(() => handleTaskUpdate(task.id, { completed: e.target.checked }))
}
style={{ marginRight: '10px' }}
/>
<span style={{
textDecoration: task.completed ? 'line-through' : 'none',
color: task.completed ? '#6c757d' : '#000'
}}>
{task.title}
</span>
</div>
<select
value={task.priority}
onChange={(e) =>
startTransition(() => handleTaskUpdate(task.id, { priority: e.target.value }))
}
style={{
padding: '4px 8px',
border: `1px solid ${priorityColors[task.priority]}`,
borderRadius: '4px',
color: priorityColors[task.priority],
backgroundColor: 'transparent',
cursor: 'pointer'
}}
>
<option value="low">Low</option>
<option value="medium">Medium</option>
<option value="high">High</option>
</select>
{task.updating && (
<span style={{
marginLeft: '10px',
color: '#007bff',
fontSize: '12px'
}}>
Saving...
</span>
)}
</div>
</div>
))}
</div>
</div>
);
}We compute the statistics from optimisticTasks, so the counters change together with the checkbox, without waiting for the server.
Advanced patterns with useOptimistic
1. Optimistic deletion with animation
This time the optimistic state does not remove the item, it marks it with a deleting flag, which leaves time for an animation:
import { useOptimistic, useState, startTransition } from 'react';
function OptimisticDeleteList() {
const [items, setItems] = useState([
{ id: 1, name: 'Item 1', createdAt: new Date() },
{ id: 2, name: 'Item 2', createdAt: new Date() },
{ id: 3, name: 'Item 3', createdAt: new Date() }
]);
const [optimisticItems, removeOptimisticItem] = useOptimistic(
items,
(currentItems, removedId) =>
currentItems.map(item =>
item.id === removedId ? { ...item, deleting: true } : item
)
);
async function handleDelete(itemId) {
// Optimistically mark as deleting
removeOptimisticItem(itemId);
// Animation before deletion
await new Promise(resolve => setTimeout(resolve, 300));
try {
const response = await fetch(`/api/items/${itemId}`, {
method: 'DELETE'
});
if (!response.ok) {
throw new Error('Deletion error');
}
// Actually remove from state
setItems(current => current.filter(item => item.id !== itemId));
} catch (error) {
// Rollback optimistic change
alert('Failed to delete item');
}
}
return (
<div style={{ maxWidth: '500px', margin: '0 auto', padding: '20px' }}>
<h2>List with optimistic deletion</h2>
<div style={{ display: 'grid', gap: '10px' }}>
{optimisticItems
.map(item => (
<div
key={item.id}
style={{
padding: '15px',
backgroundColor: '#fff',
border: '1px solid #ddd',
borderRadius: '8px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
opacity: item.deleting ? 0 : 1,
transform: item.deleting ? 'translateX(-100%)' : 'translateX(0)',
transition: 'all 0.3s ease-out',
overflow: 'hidden'
}}
>
<div>
<h4 style={{ margin: '0 0 5px 0' }}>{item.name}</h4>
<small style={{ color: '#6c757d' }}>
Created: {item.createdAt.toLocaleString('en-US')}
</small>
</div>
<button
onClick={() => startTransition(() => handleDelete(item.id))}
disabled={item.deleting}
style={{
padding: '5px 10px',
backgroundColor: '#dc3545',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: item.deleting ? 'not-allowed' : 'pointer',
opacity: item.deleting ? 0.5 : 1
}}
>
{item.deleting ? 'Deleting...' : 'Delete'}
</button>
</div>
))}
</div>
</div>
);
}The animation delay is now a plain await inside the Action. If the request sat inside setTimeout, the Action would end immediately and the deleting flag would vanish before the deletion.
2. Optimistic real-time collaboration
The shared editor combines two optimistic states with a WebSocket connection. Treat it as an architecture sketch:
import { useOptimistic, useState, useEffect, startTransition } from 'react';
function CollaborativeEditor({ documentId, userId }) {
const [content, setContent] = useState('');
const [collaborators, setCollaborators] = useState([]);
const [optimisticContent, updateOptimisticContent] = useOptimistic(
content,
(_, newContent) => newContent
);
const [optimisticCollaborators, updateOptimisticCollaborators] = useOptimistic(
collaborators,
(currentCollaborators, update) => {
if (update.type === 'cursor') {
return currentCollaborators.map(c =>
c.id === update.userId ? { ...c, cursor: update.position } : c
);
}
return currentCollaborators;
}
);
// WebSocket or other real-time connection
useEffect(() => {
const ws = new WebSocket(`ws://localhost:8080/doc/${documentId}`);
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'content-update' && data.userId !== userId) {
setContent(data.content);
} else if (data.type === 'cursor-update') {
setCollaborators(data.collaborators);
}
};
return () => ws.close();
}, [documentId, userId]);
async function handleContentChange(newContent) {
// Optimistic update
updateOptimisticContent(newContent);
try {
await fetch(`/api/documents/${documentId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ content: newContent, userId })
});
setContent(newContent);
} catch (error) {
console.error('Error saving:', error);
}
}
function handleCursorMove(position) {
updateOptimisticCollaborators({
type: 'cursor',
userId,
position
});
// Send cursor update via WebSocket
// ws.send(JSON.stringify({ type: 'cursor', position }));
}
return (
<div style={{ maxWidth: '800px', margin: '0 auto', padding: '20px' }}>
<h2>Shared Editor</h2>
<div style={{ marginBottom: '10px' }}>
<h4>Active users:</h4>
<div style={{ display: 'flex', gap: '10px' }}>
{optimisticCollaborators.map(collaborator => (
<div
key={collaborator.id}
style={{
padding: '5px 10px',
backgroundColor: collaborator.color,
color: 'white',
borderRadius: '15px',
fontSize: '12px'
}}
>
{collaborator.name}
{collaborator.cursor && (
<span style={{ marginLeft: '5px' }}>
(line {collaborator.cursor.line})
</span>
)}
</div>
))}
</div>
</div>
<textarea
value={optimisticContent}
onChange={(e) => startTransition(() => handleContentChange(e.target.value))}
onSelect={(e) => {
const position = {
line: e.target.value.substring(0, e.target.selectionStart).split('\n').length,
column: e.target.selectionStart
};
startTransition(() => handleCursorMove(position));
}}
style={{
width: '100%',
height: '400px',
padding: '15px',
border: '1px solid #ddd',
borderRadius: '8px',
fontSize: '16px',
fontFamily: 'monospace'
}}
/>
<div style={{
marginTop: '10px',
fontSize: '12px',
color: '#6c757d'
}}>
Last sync: {new Date().toLocaleTimeString('en-US')}
</div>
</div>
);
}The cursor reacts to the onSelect event, because React has no onSelectionChange event for a text field. Two warnings: react.dev advises against controlling a text field through transitions, so text typed by the user is better kept in plain state. The cursor position, in turn, does not wait for the server, so a plain useState fits it better than optimistic state.
3. Batch updates with queuing
A chat can send messages in batches of five. First the queue and its processing:
import { useOptimistic, useState, useRef, startTransition } from 'react';
function BatchedUpdatesDemo() {
const [messages, setMessages] = useState([]);
const updateQueue = useRef([]);
const isProcessing = useRef(false);
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(currentMessages, newMessage) => [...currentMessages, newMessage]
);
async function processBatch() {
if (isProcessing.current || updateQueue.current.length === 0) return;
isProcessing.current = true;
const batch = updateQueue.current.splice(0, 5); // Max 5 at a time
try {
const response = await fetch('/api/messages/batch', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ messages: batch })
});
const savedMessages = await response.json();
setMessages(current => [
...current,
...savedMessages.map(msg => ({ ...msg, sent: true }))
]);
} catch (error) {
console.error('Error sending batch:', error);
// Return to queue
updateQueue.current.unshift(...batch);
} finally {
isProcessing.current = false;
// Process next batch if there are items
if (updateQueue.current.length > 0) {
setTimeout(processBatch, 100);
}
}
}
async function sendMessage(text) {
const newMessage = {
id: Date.now(),
text,
timestamp: new Date(),
sent: false,
pending: true
};
// Optimistic update
addOptimisticMessage(newMessage);
// Add to queue
updateQueue.current.push(newMessage);
// Start processing if not active
await processBatch();
}
useRef keeps the queue outside of state, so changing it does not trigger a render. Now sending and the view:
return (
<div style={{ maxWidth: '600px', margin: '0 auto', padding: '20px' }}>
<h2>Chat with batch updates</h2>
<div style={{
height: '400px',
overflowY: 'auto',
border: '1px solid #ddd',
borderRadius: '8px',
padding: '15px',
marginBottom: '15px',
backgroundColor: '#f8f9fa'
}}>
{optimisticMessages.map(message => (
<div
key={message.id}
style={{
marginBottom: '10px',
padding: '10px',
backgroundColor: message.pending ? '#e3f2fd' : '#fff',
borderRadius: '8px',
opacity: message.pending ? 0.8 : 1,
transition: 'all 0.3s'
}}
>
<div style={{ marginBottom: '5px' }}>{message.text}</div>
<div style={{
fontSize: '12px',
color: '#6c757d',
display: 'flex',
justifyContent: 'space-between'
}}>
<span>{message.timestamp.toLocaleTimeString('en-US')}</span>
<span>
{message.pending ? 'Sending...' : 'Sent'}
</span>
</div>
</div>
))}
</div>
<form
onSubmit={(e) => {
e.preventDefault();
const input = e.target.message;
if (input.value) {
startTransition(() => sendMessage(input.value));
input.value = '';
}
}}
style={{ display: 'flex', gap: '10px' }}
>
<input
name="message"
style={{
flex: 1,
padding: '10px',
border: '1px solid #ddd',
borderRadius: '4px'
}}
/>
<button
type="submit"
style={{
padding: '10px 20px',
backgroundColor: '#007bff',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
>
Send
</button>
</form>
<div style={{
marginTop: '10px',
fontSize: '12px',
color: '#6c757d'
}}>
In queue: {updateQueue.current.length} |
Processing: {isProcessing.current ? 'Yes' : 'No'}
</div>
</div>
);
}sendMessage waits for processBatch, so the message stays optimistic until it is sent. Note: when a batch is already on its way, processBatch returns immediately, and the next message may disappear before it is sent. The queue counter also reads a ref, so it does not refresh by itself.
Practical applications of useOptimistic
1. Comment system with reactions
One reducer handles three kinds of changes: adding a comment, a reaction and a reply. First the logic:
import { useOptimistic, useState, startTransition } from 'react';
function CommentSystem({ postId }) {
const [comments, setComments] = useState([]);
const [optimisticComments, updateOptimisticComment] = useOptimistic(
comments,
(currentComments, action) => {
switch (action.type) {
case 'add':
return [...currentComments, action.comment];
case 'react':
return currentComments.map(comment =>
comment.id === action.commentId
? {
...comment,
reactions: {
...comment.reactions,
[action.reaction]: (comment.reactions[action.reaction] || 0) + 1
},
userReacted: action.reaction
}
: comment
);
case 'reply':
return currentComments.map(comment =>
comment.id === action.parentId
? {
...comment,
replies: [...(comment.replies || []), action.reply]
}
: comment
);
default:
return currentComments;
}
}
);
async function addComment(text) {
const newComment = {
id: Date.now(),
text,
author: 'You',
timestamp: new Date(),
reactions: {},
replies: [],
pending: true
};
updateOptimisticComment({ type: 'add', comment: newComment });
try {
const response = await fetch(`/api/posts/${postId}/comments`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text })
});
const savedComment = await response.json();
setComments(current => [...current, savedComment]);
} catch (error) {
console.error('Error adding comment:', error);
}
}
async function reactToComment(commentId, reaction) {
updateOptimisticComment({
type: 'react',
commentId,
reaction
});
try {
await fetch(`/api/comments/${commentId}/react`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ reaction })
});
// Update actual state
const response = await fetch(`/api/posts/${postId}/comments`);
const updatedComments = await response.json();
setComments(updatedComments);
} catch (error) {
console.error('Error reacting:', error);
}
}
const reactionLabels = {
like: 'Like',
love: 'Love',
laugh: 'Haha',
wow: 'Wow',
sad: 'Sad'
};
Every change goes through updateOptimisticComment with a type field, just like actions in useReducer. Now the view:
return (
<div style={{ maxWidth: '600px', margin: '0 auto', padding: '20px' }}>
<h3>Comments</h3>
<form
onSubmit={(e) => {
e.preventDefault();
const text = e.target.comment.value;
if (text) {
startTransition(() => addComment(text));
e.target.reset();
}
}}
style={{ marginBottom: '20px' }}
>
<textarea
name="comment"
rows="3"
style={{
width: '100%',
padding: '10px',
border: '1px solid #ddd',
borderRadius: '4px',
marginBottom: '10px'
}}
/>
<button
type="submit"
style={{
padding: '8px 16px',
backgroundColor: '#007bff',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
>
Add comment
</button>
</form>
<div style={{ display: 'grid', gap: '15px' }}>
{optimisticComments.map(comment => (
<div
key={comment.id}
style={{
padding: '15px',
backgroundColor: comment.pending ? '#f0f8ff' : '#fff',
border: '1px solid #ddd',
borderRadius: '8px',
opacity: comment.pending ? 0.8 : 1
}}
>
<div style={{ marginBottom: '10px' }}>
<strong>{comment.author}</strong>
<span style={{
marginLeft: '10px',
color: '#6c757d',
fontSize: '14px'
}}>
{comment.timestamp.toLocaleString('en-US')}
</span>
{comment.pending && (
<span style={{
marginLeft: '10px',
color: '#007bff',
fontSize: '12px'
}}>
(sending...)
</span>
)}
</div>
<p style={{ margin: '10px 0' }}>{comment.text}</p>
<div style={{ display: 'flex', gap: '10px' }}>
{Object.entries(reactionLabels).map(([reaction, label]) => (
<button
key={reaction}
onClick={() => startTransition(() => reactToComment(comment.id, reaction))}
style={{
padding: '4px 8px',
backgroundColor: comment.userReacted === reaction ? '#e3f2fd' : '#f8f9fa',
border: '1px solid #ddd',
borderRadius: '15px',
cursor: 'pointer',
fontSize: '14px',
display: 'flex',
alignItems: 'center',
gap: '4px'
}}
>
<span>{label}</span>
{comment.reactions[reaction] > 0 && (
<span>{comment.reactions[reaction]}</span>
)}
</button>
))}
</div>
{comment.replies && comment.replies.length > 0 && (
<div style={{
marginTop: '15px',
marginLeft: '20px',
paddingLeft: '15px',
borderLeft: '2px solid #e9ecef'
}}>
{comment.replies.map(reply => (
<div key={reply.id} style={{ marginBottom: '10px' }}>
<strong>{reply.author}:</strong> {reply.text}
</div>
))}
</div>
)}
</div>
))}
</div>
</div>
);
}The reaction buttons and the form run their functions inside startTransition, so the counters grow instantly.
2. Drag & Drop with optimistic sorting
Dragging items is another case where the user cannot wait for the server:
import { useOptimistic, useState, startTransition } from 'react';
function DragDropList() {
const [items, setItems] = useState([
{ id: 1, text: 'Item 1', order: 0 },
{ id: 2, text: 'Item 2', order: 1 },
{ id: 3, text: 'Item 3', order: 2 },
{ id: 4, text: 'Item 4', order: 3 }
]);
const [draggedItem, setDraggedItem] = useState(null);
const [optimisticItems, reorderOptimistic] = useOptimistic(
items,
(currentItems, { fromIndex, toIndex }) => {
const newItems = [...currentItems];
const [removed] = newItems.splice(fromIndex, 1);
newItems.splice(toIndex, 0, removed);
return newItems.map((item, index) => ({ ...item, order: index }));
}
);
async function handleDrop(fromIndex, toIndex) {
if (fromIndex === toIndex) return;
// Optimistic update
reorderOptimistic({ fromIndex, toIndex });
try {
const response = await fetch('/api/items/reorder', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ fromIndex, toIndex })
});
const reorderedItems = await response.json();
setItems(reorderedItems);
} catch (error) {
console.error('Error reordering:', error);
}
}
return (
<div style={{ maxWidth: '400px', margin: '0 auto', padding: '20px' }}>
<h2>Drag & Drop List</h2>
<div style={{
border: '1px solid #ddd',
borderRadius: '8px',
overflow: 'hidden'
}}>
{optimisticItems.map((item, index) => (
<div
key={item.id}
draggable
onDragStart={() => setDraggedItem({ item, index })}
onDragOver={(e) => e.preventDefault()}
onDrop={() => {
if (draggedItem) {
startTransition(() => handleDrop(draggedItem.index, index));
setDraggedItem(null);
}
}}
style={{
padding: '15px',
backgroundColor: '#fff',
borderBottom: '1px solid #e9ecef',
cursor: 'move',
display: 'flex',
alignItems: 'center',
transition: 'all 0.3s',
opacity: draggedItem?.item.id === item.id ? 0.5 : 1
}}
>
<span style={{
marginRight: '15px',
fontSize: '20px',
color: '#6c757d'
}}>
β‘
</span>
<span style={{ flex: 1 }}>{item.text}</span>
<span style={{
color: '#6c757d',
fontSize: '14px'
}}>
#{item.order + 1}
</span>
</div>
))}
</div>
<p style={{
marginTop: '15px',
fontSize: '14px',
color: '#6c757d',
textAlign: 'center'
}}>
Drag items to change the order
</p>
</div>
);
}The new order appears right after the drop, and the server only confirms it.
Best practices with useOptimistic
1. Data structure
Mark optimistic data so the interface can highlight it:
// GOOD - marking optimistic state
const optimisticItem = {
...originalItem,
optimistic: true, // or pending: true
optimisticId: Date.now() // for identification
};
// GOOD - preserving original data
const [optimistic, update] = useOptimistic(
realData,
(current, change) => ({
...current,
...change,
_original: current // keep the original
})
);
// BAD - no state marking
const badOptimistic = {
...originalItem
// No way to distinguish from actual data
};A pending or optimistic flag lets you show "sending" and block actions on unconfirmed items.
2. Error handling
Retrying with exponential backoff fits temporary network failures:
// Retry strategy with exponential backoff
async function optimisticUpdateWithRetry(action, maxRetries = 3) {
let lastError;
for (let i = 0; i < maxRetries; i++) {
try {
const result = await action();
return result;
} catch (error) {
lastError = error;
if (i < maxRetries - 1) {
// Exponential backoff
await new Promise(resolve =>
setTimeout(resolve, Math.pow(2, i) * 1000)
);
}
}
}
// Show error to user
showErrorNotification('Operation failed. Please try again.');
throw lastError;
}Remember that the optimistic state lasts through all the retries, because the whole function runs in a single Action.
3. Performance
Finally, two performance patterns:
// GOOD - batch updates
const [optimistic, batchUpdate] = useOptimistic(
items,
(current, updates) => {
// Process multiple updates at once
return updates.reduce((acc, update) => {
// Apply each update
return applyUpdate(acc, update);
}, current);
}
);
// Usage
function handleMultipleUpdates(updates) {
batchUpdate(updates); // One update instead of many
}
// GOOD - memoization of heavy computations
const processedOptimisticData = useMemo(() => {
return expensiveProcessing(optimisticData);
}, [optimisticData]);A single call with an array of changes gives one reducer pass instead of many.
The useOptimistic hook is the key to creating responsive applications that give the user instant feedback. Proper use of this hook can significantly improve the perceived performance of an application.
My advice: the simplest way is to use useOptimistic with a form action, because React wraps it in a transition for you. In this module's project you will combine the hook with useActionState. Remember: optimism on the bridge lasts only until the report from Mars arrives, then the real state is what counts.
Code for this lesson: App.jsx
import { useState, useOptimistic, useTransition } from 'react';
// API simulation: delayed server responses
function simulateAPI(action, data) {
return new Promise((resolve, reject) => {
setTimeout(() => {
// 10% chance of an error
if (Math.random() < 0.1) {
reject(new Error(`Server error during: ${action}`));
} else {
resolve({ success: true, data });
}
}, 1000 + Math.random() * 1500);
});
}
function MissionCard({ mission, onToggle, onDelete }) {
return (
<div style={{
padding: '14px 16px', marginBottom: '10px',
background: mission.sending
? 'rgba(0, 212, 255, 0.06)'
: mission.completed
? 'rgba(78, 205, 196, 0.08)'
: 'rgba(255, 255, 255, 0.03)',
borderRadius: '10px',
border: `1px solid ${mission.sending ? '#1a3a5c' : mission.completed ? '#2a5c3a' : '#1a2a3c'}`,
opacity: mission.sending ? 0.7 : 1,
transition: 'all 0.3s ease',
display: 'flex', alignItems: 'center', gap: '12px',
}}>
<button
onClick={() => onToggle(mission.id)}
disabled={mission.sending}
aria-pressed={mission.completed}
style={{
width: '28px', height: '28px', borderRadius: '50%',
border: `2px solid ${mission.completed ? '#4ecdc4' : '#778da9'}`,
background: mission.completed ? '#4ecdc4' : 'transparent',
cursor: mission.sending ? 'default' : 'pointer',
display: 'flex', alignItems: 'center', justifyContent: 'center',
color: '#fff', fontSize: '14px', flexShrink: 0,
}}
>
{mission.completed ? 'β' : ''}
</button>
<div style={{ flex: 1 }}>
<div style={{
color: mission.completed ? '#4ecdc4' : '#e0e1dd',
textDecoration: mission.completed ? 'line-through' : 'none',
fontSize: '15px', fontWeight: 500,
}}>
{mission.name}
</div>
<div style={{ color: '#556677', fontSize: '12px', marginTop: '2px' }}>
{mission.priority}
</div>
</div>
{mission.sending && (
<span style={{ color: '#00d4ff', fontSize: '11px', fontStyle: 'italic' }}>
Syncing...
</span>
)}
<button
onClick={() => onDelete(mission.id)}
disabled={mission.sending}
style={{
padding: '4px 8px', background: 'transparent',
border: '1px solid #5c1a1a', borderRadius: '4px',
color: '#ff6b6b', cursor: mission.sending ? 'default' : 'pointer',
fontSize: '12px',
}}
>
Delete
</button>
</div>
);
}
export default function App() {
const [missions, setMissions] = useState([
{ id: 1, name: 'Explore the orbit of Mars', completed: false, priority: 'High' },
{ id: 2, name: 'Repair the communications module', completed: true, priority: 'Critical' },
{ id: 3, name: 'Collect samples from Io', completed: false, priority: 'Medium' },
{ id: 4, name: 'Calibrate the telescope', completed: false, priority: 'Low' },
]);
const [newMission, setNewMission] = useState('');
const [error, setError] = useState(null);
const [isPending, startTransition] = useTransition();
// useOptimistic - instant UI updates
const [optimisticMissions, addOptimistic] = useOptimistic(
missions,
// Reducer: (current state, optimistic change) => new optimistic state
(currentMissions, optimisticUpdate) => {
switch (optimisticUpdate.type) {
case 'toggle':
return currentMissions.map(m =>
m.id === optimisticUpdate.id
? { ...m, completed: !m.completed, sending: true }
: m
);
case 'add':
return [...currentMissions, { ...optimisticUpdate.mission, sending: true }];
case 'delete':
return currentMissions.map(m =>
m.id === optimisticUpdate.id ? { ...m, sending: true } : m
);
default:
return currentMissions;
}
}
);
// Every change is an Action in startTransition: the optimistic state lasts until the async function finishes
function handleToggle(id) {
setError(null);
startTransition(async () => {
addOptimistic({ type: 'toggle', id });
try {
await simulateAPI('toggle', { id });
// We wrap the update after await in another startTransition, as react.dev advises
startTransition(() => {
setMissions(prev =>
prev.map(m => m.id === id ? { ...m, completed: !m.completed } : m)
);
});
} catch (err) {
// Error: we change nothing, the optimistic state disappears by itself when the Action ends
setError(`Could not change the mission status (ID: ${id})`);
}
});
}
function handleAdd(e) {
e.preventDefault();
const name = newMission.trim();
if (!name) return;
setError(null);
setNewMission('');
const tempMission = { id: Date.now(), name, completed: false, priority: 'Medium' };
startTransition(async () => {
addOptimistic({ type: 'add', mission: tempMission });
try {
await simulateAPI('add', tempMission);
startTransition(() => {
setMissions(prev => [...prev, tempMission]);
});
} catch (err) {
setError('Could not add the mission');
}
});
}
function handleDelete(id) {
setError(null);
startTransition(async () => {
addOptimistic({ type: 'delete', id });
try {
await simulateAPI('delete', { id });
startTransition(() => {
setMissions(prev => prev.filter(m => m.id !== id));
});
} catch (err) {
setError(`Could not delete the mission (ID: ${id})`);
}
});
}
const completed = optimisticMissions.filter(m => m.completed).length;
const total = optimisticMissions.length;
return (
<div style={{
minHeight: '100vh',
background: 'linear-gradient(135deg, #0a0e27 0%, #1a1a3e 100%)',
padding: '24px', fontFamily: 'monospace',
}}>
<h1 style={{ color: '#00d4ff', textAlign: 'center', marginBottom: '4px' }}>
useOptimistic - Space missions
</h1>
<p style={{ color: '#778da9', textAlign: 'center', marginBottom: '24px', fontSize: '13px' }}>
Changes visible immediately, synchronization in the background
</p>
<div style={{ maxWidth: '550px', margin: '0 auto' }}>
<div style={{
marginBottom: '20px', padding: '14px',
background: 'rgba(0, 212, 255, 0.06)', borderRadius: '10px',
}}>
<div style={{
display: 'flex', justifyContent: 'space-between',
marginBottom: '8px', fontSize: '13px', color: '#c0c8d0',
}}>
<span>Mission progress {isPending && <em style={{ color: '#00d4ff' }}>(syncing)</em>}</span>
<span>{completed}/{total} completed</span>
</div>
<div style={{
height: '8px', background: '#1a2a3c', borderRadius: '4px', overflow: 'hidden',
}}>
<div style={{
height: '100%', width: `${total > 0 ? (completed / total) * 100 : 0}%`,
background: 'linear-gradient(90deg, #00d4ff, #4ecdc4)',
borderRadius: '4px', transition: 'width 0.3s ease',
}} />
</div>
</div>
<form onSubmit={handleAdd} style={{
display: 'flex', gap: '8px', marginBottom: '20px',
}}>
<input
value={newMission}
onChange={e => setNewMission(e.target.value)}
placeholder="New mission..."
style={{
flex: 1, padding: '10px 14px', background: '#0d1b2a',
border: '1px solid #1a3a5c', borderRadius: '8px',
color: '#e0e1dd', fontSize: '14px',
}}
/>
<button type="submit" style={{
padding: '10px 20px', background: '#1a3a5c',
border: 'none', borderRadius: '8px', color: '#00d4ff',
cursor: 'pointer', fontSize: '13px', whiteSpace: 'nowrap',
}}>
+ Add
</button>
</form>
{error && (
<div role="alert" style={{
padding: '10px 14px', marginBottom: '12px',
background: 'rgba(255, 107, 107, 0.1)', borderRadius: '8px',
border: '1px solid #5c1a1a', color: '#ff6b6b', fontSize: '13px',
}}>
{error}
</div>
)}
{optimisticMissions.map(mission => (
<MissionCard
key={mission.id}
mission={mission}
onToggle={handleToggle}
onDelete={handleDelete}
/>
))}
<div style={{
marginTop: '20px', padding: '14px',
background: 'rgba(255, 215, 0, 0.06)', borderRadius: '10px',
fontSize: '12px', color: '#c0c8d0', lineHeight: '1.7',
}}>
<strong style={{ color: '#ffd700' }}>How useOptimistic works:</strong>
<ul style={{ margin: '8px 0', paddingLeft: '18px' }}>
<li>The UI updates immediately (optimistically)</li>
<li>Synchronization with the server runs in the background (1-2.5 s)</li>
<li>On an error (10% chance) the optimistic state disappears and the real state comes back</li>
<li>The "Syncing..." indicator shows that an Action is running</li>
</ul>
</div>
</div>
</div>
);
}Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is the useTransition hook used for in React?
2. What happens with an optimistic UI update (useOptimistic) when the server request returns an error?
These are 2 of 9 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Vertical ordering
Arrange the code of a component that connects a label with a field using useId:
- Vertical ordering
Arrange the correct syntax for using useTransition:
- Code editor
The chat with the Luna base sends messages through the form action sendMessage. The link answers after 0.6 s, and a message that starts with ! pretends to hit interference and ends with an error. Fill in the blanks: ___BLANK1___ is the React 19 hook that creates an optimistic state from the real messages list and a function that appends a message, ___BLANK2___ is the function you use to show the message right away, before the base answers, and ___BLANK3___ is the list you display in the <ul>. A sent message should appear immediately with a sending note, stay without the note after the confirmation, and on an error disappear and leave a message.
- Vertical ordering
Arrange the stages of one React render cycle in order:
- Vertical ordering
Arrange the steps of loading data with the use() hook and Suspense:
- Click in order
Arrange the syntax of the useCallback hook for stabilizing function references:
- Vertical ordering
Where does performance optimization start? Arrange the steps: the first step is fixed, the order of the techniques after it depends on what the measurement shows.
- Horizontal ordering
Arrange the destructuring syntax of the useOptimistic hook:
- Vertical ordering
Arrange the stages of the build optimization pipeline from analysis to delivery:
- Code editor
A bundle analyzer (e.g. rollup-plugin-visualizer in Vite) saved the sizes of the app modules after compression. Complete the report: ___BLANK1___ is the size of a single module (a field of the item object) that reduce adds to the sum, ___BLANK2___ is the compare expression that orders the modules from the biggest to the smallest, and ___BLANK3___ is the condition that is true for a module bigger than the BUDGET. The report should show a total size of 742 kB, a list from star-map (310 kB) to navigation (24 kB), and with the checkbox ticked only the three modules above 100 kB, the candidates for splitting out with lazy().
- Click in order
Arrange the syntax of the React Profiler component for measuring performance (the id attribute before onRender):
- Vertical ordering
Arrange the steps for diagnosing performance with React Profiler:
- Code editor
The gallery shows pictures of three planets. Every picture has a small, blurred thumbnail visible right away and a full image that appears only after it has loaded. Complete the PlanetImage component: ___BLANK1___ is the value of the loading attribute that makes the browser download the full image only when it gets close to the screen, ___BLANK2___ is the status set after the load event (the thumbnail disappears and the picture becomes visible), and ___BLANK3___ is the call that sets the status 'error' after the error event. Every picture has its own state, and an error shows a message with the planet name.
- Horizontal ordering
Arrange the syntax of an img element with the lazy loading attribute:
- Code editor
The TelemetryChart renders hundreds of bars, and the button adds more. Measure its renders with the Profiler component: ___BLANK1___ is the third parameter of the callback, the render time in milliseconds (the name is already used in the function body), ___BLANK2___ is the React component that measures the renders of its subtree, and ___BLANK3___ is the function passed to its onRender attribute. After mounting, an entry with the mount phase should appear in the console, and after clicking the button an entry with the update phase.
- Click in order
Arrange the declaration of a lazy-loaded component with React.lazy:
- Vertical ordering
Arrange the lazy loading implementation in order:
- Code editor
The hyperspace jump calculator computes the fuel use in a worker thread, so that the interface does not freeze. The thread has the Web Worker API: postMessage sends data, onmessage receives the result and terminate stops the thread (in the preview the createWorker function imitates it). Fill in the blanks: ___BLANK1___ is the field of the event object that carries the result, ___BLANK2___ is the method the effect cleanup uses to stop the thread, and ___BLANK3___ is the method the click uses to send the distance to the thread. The thread should be created once after mounting, the button should stay disabled until the answer comes, and the result should appear on the screen.
- Click in order
Arrange the Performance Observer setup in order:
- Code editor
The cacheFirst, networkFirst and pickStrategy functions go into the sw.js file and handle the fetch event in the Service Worker. Static files should use the cache-first strategy (a copy from the cache first, the network only when there is no copy), and data from /api/ the network-first strategy (a fresh response from the network first, a copy from the cache only when offline). Fill in the blanks: ___BLANK1___ is the cache method that looks for a saved response, ___BLANK2___ is the cache method that saves a response, and ___BLANK3___ is the strategy function that pickStrategy returns for /api/ addresses. The panel in the preview lets you switch the network off and check where the responses come from.
- Code editor
The report form for Mission Control uses useActionState, and the submit button is a separate SubmitButton component that should know by itself that the form is being sent. Fill in the blanks: ___BLANK1___ is the field returned by the hook that is true while sending, ___BLANK2___ is the react-dom hook that reads the state of the form the component is rendered in, ___BLANK3___ is the button component placed in the form, and ___BLANK4___ is the status the action returns for a report that is too short. A report shorter than 10 characters should show an error, a longer one a confirmation, and during the transmission the button should be disabled and change its label.
Tasks after this lesson
- QuestionuseTransition for Non-Urgent Updates
- Put in orderuseId Syntax for Accessibility
- Put in orderuseTransition Syntax
- Coding taskPractice: Optimistic UI Updates
- Put in orderReact Rendering Cycle
- Put in orderuse() with Suspense Flow
- QuestionuseOptimistic - Rollback on Error
- Click in orderuseCallback Syntax
- Put in orderPerformance Optimization Stages
- Questionuse() Hook vs useContext
- QuestionConcurrent rendering in React
- Put in orderuseOptimistic Syntax
- QuestionuseDeferredValue vs useTransition
- Put in orderBuild Optimization Pipeline
- QuestionReact 18+ Hooks
- Coding taskPractice: Bundle Analysis
- Click in orderProfiler Component Syntax
- QuestionImport Impact on Bundle Size
- Put in orderReact Profiler Workflow
- Coding taskPractice: Lazy Loading Images
- Put in orderLazy Loading Image Syntax
- Coding taskPractice: React Profiler
- Click in orderReact.lazy Syntax
- Put in orderLazy Loading Implementation with Suspense
- Coding taskPractice: Web Workers
- QuestionDynamic Import in React
- Click in orderPerformance Monitoring Configuration
- Coding taskPractice: Service Worker
- QuestionAutomatic Batching and setTimeout
- Coding taskPractice: useActionState and useFormStatus