Optimistic Updates with useOptimistic
What you'll learn: How to show instant UI feedback while waiting for server confirmation by optimistically updating your UI before the server responds.
The Core Problem
When you submit a form using Server Actions, there's a network delay before the server responds. Without optimistic updates, users see a loading state and wait. With optimistic updates, you show the expected result immediately, creating the illusion of instant response.
How useOptimistic Works
The useOptimistic hook lets you display a temporary "optimistic" version of your data while the real server mutation is in progress. Think of it like paying with a credit card: the cashier hands you the receipt immediately, even though the bank hasn't actually transferred the money yet.
'use client'
import { useOptimistic } from 'react'
function TodoList({ todos, addTodo }) {
const [optimisticTodos, addOptimisticTodo] = useOptimistic(
todos,
(state, newTodo) => [...state, newTodo]
)
async function handleSubmit(formData) {
const text = formData.get('text')
addOptimisticTodo({ id: Date.now(), text, pending: true })
await addTodo(formData) // Server Action
}
return (
<form action={handleSubmit}>
{optimisticTodos.map(todo => (
<div key={todo.id} style={{ opacity: todo.pending ? 0.5 : 1 }}>
{todo.text}
</div>
))}
<input name="text" />
<button>Add</button>
</form>
)
}
The first argument is the actual data. The second is an updater function that computes the optimistic state. When the server responds, React automatically replaces the optimistic state with the real data.
Key Takeaway: useOptimistic lets you show instant UI feedback by temporarily displaying the expected outcome while the server processes your request, automatically reverting if the server returns different data.