Nextjs Fundamentals · Server Functions & Mutations

Optimistic updates

useOptimistic

Optimistic updates

An optimistic update shows the result of a mutation before the server confirms it, so the UI feels instant. React's useOptimistic hook lets a Client Component hold a temporary value while a Server Function is in flight.

'use client';

import { useOptimistic } from 'react';
import { addTodo } from '@/app/actions';

export function TodoList({ todos }) {
  const [optimisticTodos, addOptimisticTodo] = useOptimistic(todos, (current, newTitle) => [
    ...current,
    { title: newTitle, sending: true },
  ]);

  return (
    <form
      action={async (formData) => {
        addOptimisticTodo(formData.get('title'));
        await addTodo(formData);
      }}
    >
      <input name="title" />
      <button>Add</button>
      <ul>
        {optimisticTodos.map((todo) => (
          <li key={todo.title}>{todo.title}</li>
        ))}
      </ul>
    </form>
  );
}

The optimistic value exists only while the action runs. Once the Server Function returns and any revalidated data arrives, React discards the temporary value and renders the real one — so the list settles on the server's truth. Call the optimistic updater inside the action (or a transition), never during plain render.

You are about to answer a short quiz on useOptimistic.

  1. useOptimistic shows a temporary value while a Server Function is in flight.
  2. Once the action resolves and revalidated data arrives, the optimistic value is replaced by the ___ one.
  3. You should call the optimistic updater during plain render.
  4. useOptimistic is a hook for ___ Components.
  5. An optimistic update makes the UI feel instant by not waiting for the server to confirm.