Course contentsShow
← React
Lesson 1853 of 2,39643. RoutingFree lesson

Optimistic UI with useFetcher

Submitting forms without navigation using fetcher.Form and accessing optimistic data.

Optimistic UI with useFetcher

What you'll learn: How to create instant-feeling interfaces by using useFetcher to update the UI before server confirmation arrives.

The Core Idea

While useNavigation tracks page-level navigation states, useFetcher handles non-navigational mutations—submitting forms or triggering actions without leaving the current page. This makes it perfect for optimistic UI patterns: you can immediately update what the user sees based on their submission data (fetcher.formData), then let the server's response replace it when ready.

Think of it like texting: your message appears instantly in the chat (optimistic), but might show a loading indicator until the server confirms it sent (revalidation).

How It Works

useFetcher gives you fetcher.formData during submission—the exact data the user just submitted. You can use this to render the "optimistic" version immediately:

function TodoItem({ todo }) {
  const fetcher = useFetcher();
  
  // Use optimistic data if submitting, otherwise show real data
  const isComplete = fetcher.formData 
    ? fetcher.formData.get("completed") === "true"
    : todo.completed;
  
  return (
    <fetcher.Form method="post" action={`/todos/${todo.id}`}>
      <input type="hidden" name="completed" value={!isComplete} />
      <button type="submit">
        {isComplete ? "✓" : "○"} {todo.title}
      </button>
    </fetcher.Form>
  );
}

When the user clicks, isComplete flips instantly using fetcher.formData. After the action completes and revalidation runs, the real data from the loader takes over. If the server disagreed, the UI automatically corrects itself.

Why This Matters

Multiple fetchers can run simultaneously without blocking navigation—perfect for "like" buttons, checkboxes, or quick edits scattered across a page.

Key Takeaway: useFetcher enables optimistic UI by giving you access to submission data (fetcher.formData) immediately, letting you show instant feedback while the server processes in the background.