typescriptintermediate

useOptimistic for Instant UI Updates

Use useOptimistic hook for instant UI feedback while server actions process in the background.

typescript
'use client';

import { useOptimistic } from 'react';

interface Todo {
  id: string;
  text: string;
  completed: boolean;
}

async function toggleTodo(id: string) {
  'use server';
  // Update in database...
  await new Promise((r) => setTimeout(r, 1000));
}

export default function TodoList({ todos }: { todos: Todo[] }) {
  const [optimisticTodos, addOptimistic] = useOptimistic(
    todos,
    (state: Todo[], updatedId: string) =>
      state.map((todo) =>
        todo.id === updatedId
          ? { ...todo, completed: !todo.completed }
          : todo
      )
  );

  async function handleToggle(id: string) {
    addOptimistic(id); // Instant UI update
    await toggleTodo(id); // Server update in background
  }

  return (
    <ul>
      {optimisticTodos.map((todo) => (
        <li key={todo.id} className="flex items-center gap-2">
          <input
            type="checkbox"
            checked={todo.completed}
            onChange={() => handleToggle(todo.id)}
          />
          <span className={todo.completed ? 'line-through text-gray-400' : ''}>
            {todo.text}
          </span>
        </li>
      ))}
    </ul>
  );
}

Use Cases

  • todo lists
  • like buttons
  • instant feedback patterns

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.