Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 39 ยท Actions and Forms

Optimistic UI and File Uploads

Make interfaces feel instant with optimistic UI from fetcher.formData in React Router v7, roll back on failure, and handle file uploads safely in actions.

Waiting for a server round trip before updating the screen makes an app feel slow, even when the server is fast. Optimistic UI shows the expected result immediately and corrects it if the request fails. React Router makes this easy because the in-flight submission is available as fetcher.formData (or navigation.formData), so you derive the display from what the user just submitted, with no extra state.

The framework cannot run on this site, so the TSX is read-only; the stand-ins demonstrate the logic and the file-handling APIs in plain JavaScript.

Deriving optimistic state

TSX
import { useFetcher } from "react-router";

function TodoItem({ todo }: { todo: { id: string; title: string; done: boolean } }) {
  const fetcher = useFetcher();

  // while submitting, trust the pending form; otherwise trust the loader data
  const done = fetcher.formData ? fetcher.formData.get("done") === "true" : todo.done;

  return (
    <fetcher.Form method="post" action={`/todos/${todo.id}`}>
      <input type="hidden" name="done" value={String(!done)} />
      <button aria-pressed={done}>{done ? "Done" : "Mark done"}</button>
      <span style={{ textDecoration: done ? "line-through" : "none" }}>{todo.title}</span>
    </fetcher.Form>
  );
}

How it works: when the fetcher submits, fetcher.formData holds the form values, so the UI immediately shows the new value. When the action finishes and the loaders revalidate, fetcher.formData becomes undefined again and the real data from the server takes over. If the action failed, the real data still has the old value, so the UI rolls back by itself. No rollback code is needed.

JS Stand-in: optimistic value with automatic rollback

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Optimistic lists

For a "create" you can render the pending item from formData too. Use useFetchers() to find all in-flight submissions to a route and append them to the loader's list:

TSX
const fetchers = useFetchers();
const pending = fetchers
  .filter((f) => f.formAction === "/comments" && f.formData)
  .map((f) => ({ id: "pending-" + f.key, text: String(f.formData!.get("text")), pending: true }));
const comments = [...loaderData.comments, ...pending];

Style pending items differently (grey text, a small "sending" label) so users know they are not saved yet. Use optimism only where the action usually succeeds. For payments, show a real pending state.

Uploading files

HTML forms send files with enctype="multipart/form-data". React Router's <Form> accepts encType for that.

TSX
<Form method="post" encType="multipart/form-data">
  <input type="file" name="avatar" accept="image/png,image/jpeg" />
  <button>Upload</button>
</Form>

In the action, request.formData() returns a File for that field. Check it before storing:

TSX
export async function action({ request }: Route.ActionArgs) {
  const form = await request.formData();
  const file = form.get("avatar");

  if (!(file instanceof File) || file.size === 0) {
    return data({ error: "Choose a file" }, { status: 400 });
  }
  if (!["image/png", "image/jpeg"].includes(file.type)) {
    return data({ error: "Only PNG or JPEG" }, { status: 400 });
  }
  if (file.size > 2 * 1024 * 1024) {
    return data({ error: "Max 2 MB" }, { status: 413 });
  }

  const bytes = new Uint8Array(await file.arrayBuffer());
  await storeAvatar(userId, bytes);           // object storage, not the database for big files
  return redirect("/profile");
}

request.formData() buffers the whole upload in memory, which is fine for small images. For large files use a streaming parser (the @remix-run/form-data-parser package or your server's own multipart handling) that hands you a stream per file and lets you enforce a size limit while receiving.

JS Stand-in: validating an uploaded file in an action

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Upload safety checklist

  • Do not trust file.type or file.name. They come from the client. For images, sniff the first bytes (the "magic number") or decode with an image library before accepting.
  • Generate your own file names. Never use the client's name as a path; it may contain ../.
  • Store files outside the web root or in object storage, and serve them with the correct Content-Type and Content-Disposition.
  • Limit size at the reverse proxy and again in code.
  • Scan or re-encode user images if they are shown to others.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does the optimistic value come from?

    While submitting, the pending form data is the expected new state.
  2. 2. What happens to the optimistic UI if the action fails?

    Deriving the display from formData means rollback is automatic.
  3. 3. Which attribute lets a form send files?

    multipart/form-data is the encoding that carries file parts.
  4. 4. Why not trust file.type?

    Verify content by inspecting bytes or decoding the file.

Summary

  • Derive optimistic UI from fetcher.formData; failure rolls back automatically.
  • Use useFetchers() to show pending creates; mark them as unsaved.
  • Upload with encType="multipart/form-data"; validate presence, type, size, and content in the action.
  • Generate your own file names and stream large uploads.

Next: Error Boundaries in Routes