useOptimistic shows optimistic state while an async action is in progress. The UI updates immediately when the user acts, then reverts or updates to the real state when the server responds.
How it works:
addOptimistic() is called — UI updates instantly with the optimistic stateComplete code example:
1import { useOptimistic } from "react";23interface Todo {4 id: string;5 text: string;6 done: boolean;7 pending?: boolean;8}910function TodoList({11 todos,12 addTodo,13}: {14 todos: Todo[];15 addTodo: (text: string) => Promise<void>;16}) {17 const [optimisticTodos, addOptimisticTodo] = useOptimistic(18 todos,19 (state: Todo[], newTodoText: string) => [20 ...state,21 {22 id: "temp-" + Date.now(),23 text: newTodoText,24 done: false,25 pending: true,26 },27 ]28 );2930 const handleSubmit = async (formData: FormData) => {31 const title = formData.get("title") as string;32 addOptimisticTodo(title); // Show immediately33 await addTodo(title); // Server action34 };3536 return (37 <div>38 <form action={handleSubmit}>39 <input name="title" placeholder="New todo..." required />40 <button type="submit">Add</button>41 </form>42 <ul>43 {optimisticTodos.map(todo => (44 <li45 key={todo.id}46 style={{ opacity: todo.pending ? 0.5 : 1 }}47 >48 {todo.text}49 {todo.pending && <span> (saving...)</span>}50 </li>51 ))}52 </ul>53 </div>54 );55}
Parameters:
state — the current state (from server or parent component)updateFn(currentState, optimisticValue) — function that returns the optimistic stateReturns:
optimisticState — state with optimistic updates appliedaddOptimistic(optimisticValue) — function to trigger the optimistic updateUse cases:
Key benefits: