C.W.K.
Stream
Lesson 07 of 08 · published

Optimistic Updates

~20 min · useOptimistic, instant UI

Level 0Curious
0 XP0/68 lessons0/11 achievements
0/120 XP to next level120 XP to go0% complete

Make "optimistic" declarative

useOptimistic lets you show the expected outcome of an action before the server confirms. The hook gives you a temporary "pretend" state that reverts automatically if the action fails.

Shape

const [optimistic, addOptimistic] = useOptimistic(realState, reducer). Call addOptimistic with the change, then run the action. The optimistic state holds until the action resolves and the cache revalidates.

Patterns where it pays

  • Likes, hearts, favorites — immediate feedback feels essential.
  • Toggles where the round-trip is >100ms.
  • Adding items to a list (with a sending… indicator).

Code

Optimistic todo list·tsx
'use client';
import { useOptimistic } from 'react';
import { addTodo } from '@/app/actions';

type Todo = { id: string; text: string; sending?: boolean };

export function TodoList({ todos }: { todos: Todo[] }) {
  const [optimistic, addOptimistic] = useOptimistic(
    todos,
    (state, newText: string) => [
      ...state,
      { id: crypto.randomUUID(), text: newText, sending: true },
    ]
  );

  async function handleSubmit(formData: FormData) {
    const text = formData.get('text') as string;
    addOptimistic(text);          // instantly visible
    await addTodo(formData);      // background
  }

  return (
    <>
      <ul>
        {optimistic.map(t => (
          <li key={t.id} style={{ opacity: t.sending ? 0.5 : 1 }}>
            {t.text}{t.sending && <span className="ml-2 text-xs">saving&hellip;</span>}
          </li>
        ))}
      </ul>
      <form action={handleSubmit}>
        <input name="text" required />
        <button>Add</button>
      </form>
    </>
  );
}

External links

Exercise

Add optimistic UI to a like-button or favorite-toggle in your app. On a deliberately throttled network, show that the click feels instant.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.