Skip to content

Add optimistic updates without races

Render the new state before the server confirms; roll back on failure. Pattern works for create / update / delete.

Optimistic updates are what make a UI feel native. The user clicks a checkbox, the row updates instantly, and the request goes out in the background. If the server agrees, nothing visible happens. If it rejects, the change rolls back. Done well, the latency disappears entirely. Done poorly, you confuse users about what is real.

The naive (pessimistic) version

Most code starts here: send the request, wait for the response, then update the UI. Easy to write, but every action has the round-trip latency built in.

async function toggleStatus(id, current) {
  setBusy(true);
  const next = current === "active" ? "inactive" : "active";
  const res = await fetch(`https://gorest.co.in/public/v3/users/${id}`, {
    method: "PATCH",
    headers,
    body: JSON.stringify({ status: next })
  });
  if (res.ok) {
    const updated = await res.json(); // v3 answers with the user itself
    setUsers(users => users.map(u => u.id === id ? updated : u));
  }
  setBusy(false);
}

Here headers is { Authorization: "Bearer <token>", "Content-Type": "application/json" }. v3 accepts the token only in the Authorization header, and a write needs a token with the users:write scope. v3 has no PUT; PATCH changes only the fields you send.

Average API latency on a public service like GoRest is 100-300 ms. That much delay between a click and a UI change feels broken on every fast network. The fix is to update the UI first.

The optimistic version

Four steps:

  1. Apply optimistically. Update the local state as if the request already succeeded.
  2. Send the request. Fire the API call.
  3. Reconcile. When the response arrives, replace the optimistic copy with the server's truth (in case any field changed).
  4. Roll back on failure. If the server rejects, restore the previous state and tell the user.
async function toggleStatus(id, current) {
  const next = current === "active" ? "inactive" : "active";
  const previous = users.find(u => u.id === id);

  // 1. Apply optimistically
  setUsers(users => users.map(u =>
    u.id === id ? { ...u, status: next } : u
  ));

  try {
    // 2. Send to server
    const res = await fetch(`https://gorest.co.in/public/v3/users/${id}`, {
      method: "PATCH",
      headers,
      body: JSON.stringify({ status: next })
    });
    if (!res.ok) throw new Error(`Got ${res.status}`);

    // 3. Reconcile with the server's truth
    const updated = await res.json();
    setUsers(users => users.map(u => u.id === id ? updated : u));
  } catch (err) {
    // 4. Roll back on failure
    setUsers(users => users.map(u => u.id === id ? previous : u));
    showToast("Could not save; reverted.");
  }
}

Notice we capture previous before changing the state; if the request fails, we put it back. The toast on rollback is essential: users need to know their action did not stick.

Optimistic create

The hard case. The new row needs an id before the server has issued one. Use a temporary id, and swap it for the real one when the response arrives.

async function createUser(input) {
  const tempId = `temp-${Date.now()}`;
  const optimistic = { id: tempId, ...input, _pending: true };

  setUsers(prev => [optimistic, ...prev]);

  try {
    const res = await fetch("https://gorest.co.in/public/v3/users", {
      method: "POST", headers, body: JSON.stringify(input)
    });
    if (!res.ok) throw new Error(`Got ${res.status}`);

    const real = await res.json();
    setUsers(prev => prev.map(u => u.id === tempId ? real : u));
  } catch (err) {
    setUsers(prev => prev.filter(u => u.id !== tempId));
    showToast("Could not create user.");
  }
}

The tempId is only a placeholder. The real id is a UUID string that the server makes, so the swap on response is needed. v3 answers 201 with the new user and a Location header. Add an Idempotency-Key header (any UUID) to the POST. If the network drops and you retry with the same key, the server returns the first answer and does not create a second user.

The _pending flag is optional but useful: render the row at half opacity until the server confirms, so the user knows it is not fully saved.

Optimistic delete

Easy: remove from the list, restore on error.

async function deleteUser(id) {
  const previous = users;
  setUsers(prev => prev.filter(u => u.id !== id));

  try {
    const res = await fetch(`https://gorest.co.in/public/v3/users/${id}`, {
      method: "DELETE", headers
    });
    if (!res.ok && res.status !== 404) throw new Error();
  } catch (err) {
    setUsers(previous); // restore everything
    showToast("Delete failed; restored.");
  }
}

v3 answers 204 with no body. Treat 404 as success: the row is gone, which is what we wanted. A 403 means the row is read only sample data, so restore it and say so.

With React Query

If you are using React Query / TanStack Query, optimistic updates are built in. Define onMutate, onError, and onSettled. The library handles the rollback wiring.

import { useMutation, useQueryClient } from "@tanstack/react-query";

function useToggleStatus() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ id, status }) => fetch(`https://gorest.co.in/public/v3/users/${id}`, {
      method: "PATCH", headers, body: JSON.stringify({ status })
    }).then(r => r.json()),

    onMutate: async ({ id, status }) => {
      await qc.cancelQueries({ queryKey: ["users"] });
      const previous = qc.getQueryData(["users"]);
      qc.setQueryData(["users"], (rows) =>
        rows.map(r => r.id === id ? { ...r, status } : r)
      );
      return { previous };
    },

    onError: (err, vars, ctx) => {
      qc.setQueryData(["users"], ctx.previous);
    },

    onSettled: () => {
      qc.invalidateQueries({ queryKey: ["users"] });
    }
  });
}

Safe updates with ETag and If-Match

Every v3 item carries an ETag header. Send it back as If-Match on PATCH or DELETE. If someone else changed the item in between, the server answers 412 and changes nothing. That is the right signal to roll back and reload.

async function toggleStatus(user, next) {
  const res = await fetch(`https://gorest.co.in/public/v3/users/${user.id}`, {
    method: "PATCH",
    headers: { ...headers, "If-Match": user.etag },
    body: JSON.stringify({ status: next })
  });
  if (res.status === 412) throw new Error("Changed elsewhere; reloading.");
  if (!res.ok) throw new Error(`Got ${res.status}`);
  return { ...(await res.json()), etag: res.headers.get("etag") };
}

Keep the ETag of each row next to the row when you read it (res.headers.get("etag") on GET /users/{id}), and replace it with the new ETag from every write response. Note that the ETag on a list is for the whole list, not for one row. Read the row itself first.

The race condition

Optimistic updates can race. The user clicks a toggle twice fast, the second click sees the optimistic state of the first, and what happens? Three options:

  • Disable controls while busy. Simplest. The user cannot click twice.
  • Cancel the previous request. Use AbortController; whichever finishes last wins.
  • Sequence them. Queue updates and send them one at a time.

For most UIs, option 1 (disable while busy) is enough. Option 3 is right for collaborative editors and similar tools.

When NOT to be optimistic

  • Anything destructive that needs confirmation. Deleting an account is not optimistic; the user agrees first.
  • Anything where partial state would mislead. Bank transfers, payments, anything legally binding: wait for the real response.
  • When the server commonly rejects. If 30% of submissions fail validation, optimistic UI flickers a lot. Pessimistic is calmer.

Test the rollback path

The whole point of optimistic UI is that errors are rare and rollback is rarer. That makes it easy to ship a broken rollback. Use GoRest's status tool to trigger failures on purpose. GET /public/v3/http/status/<code> answers with that code, as Problem Details for 4xx and 5xx. Point your save function at it for one test and confirm your rollback restores correctly:

fetch("https://gorest.co.in/public/v3/http/status/500")

To test a slow save, use https://gorest.co.in/public/v3/http/delay/2000. It waits 2 seconds and then answers. You can also test the 412 path for real: send a wrong If-Match value on a PATCH to one of your own rows.

More recipes

Keep building