Mutations and optimistic UI

Topic 4 of 4 in Data fetching6 min readIntermediateFree course

Overview

Reading data is half the job. The other half is changing it: enrolling in a course, posting a comment, deleting a lesson. These are mutations. Doing them well means three things: tracking pending and error states, making sure every part of the UI shows the new data afterwards, and — for small, likely-to-succeed actions — updating the screen before the server even answers.

Mutations with TanStack Query

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

async function enrol(courseId) {
  const res = await fetch('/api/enrolments', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ courseId }),
  });
  if (!res.ok) throw new Error('Enrolment failed');
  return res.json();
}

function EnrolButton({ courseId }) {
  const queryClient = useQueryClient();

  const mutation = useMutation({
    mutationFn: enrol,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['enrolments'] });
      queryClient.invalidateQueries({ queryKey: ['courses', courseId] });
    },
  });

  return (
    <>
      <button onClick={() => mutation.mutate(courseId)} disabled={mutation.isPending}>
        {mutation.isPending ? 'Enrolling…' : 'Enrol'}
      </button>
      {mutation.isError && <p role="alert">{mutation.error.message}</p>}
      {mutation.isSuccess && <p role="status">You’re in! 🎉</p>}
    </>
  );
}
  • useMutation doesn’t run anything until you call mutate(variables) (or await mutateAsync(variables)).
  • It tracks isPending, isError, error, isSuccess and data.
  • Mutations are not retried by default — repeating a POST could create duplicates.

Invalidation

After enrolling, the “My courses” list and the course’s seat count are out of date. invalidateQueries marks matching queries as stale and refetches any that are on screen. Keys match by prefix, so { queryKey: ['courses'] } invalidates ['courses'], ['courses', 7] and ['courses', { q: 'react' }].

Invalidation is the simplest correct approach: let the server tell you the new truth. If the mutation’s response already contains the updated object, you can write it straight into the cache instead and save a request:

JSX
onSuccess: (updatedCourse) => {
  queryClient.setQueryData(['courses', updatedCourse.id], updatedCourse);
},

Optimistic UI

Some actions almost always succeed — liking a post, ticking off a lesson, starring a course. Waiting 300 ms for the server before showing the change makes the app feel sluggish. Optimistic UI updates the screen immediately and reconciles with the server afterwards:

On the UI lane, a click on the heart changes the count from 41 to 42 and the UI shows 42 immediately (optimistic). On the server lane, POST /like takes about 300 ms. On success the UI keeps 42; on failure it rolls back to 41 and shows a toast. The code uses useOptimistic(likes, (n, delta) => n + delta) and a startTransition that calls addOptimistic(1) and awaits likePost(id).

useOptimistic

React 19’s useOptimistic hook shows a temporary value while an action is in progress:

JSX
import { useOptimistic, useState, startTransition } from 'react';

function LessonCheckbox({ lesson, saveCompleted }) {
  const [completed, setCompleted] = useState(lesson.completed);
  const [optimisticCompleted, setOptimisticCompleted] = useOptimistic(completed);

  function handleChange(e) {
    const next = e.target.checked;
    startTransition(async () => {
      setOptimisticCompleted(next);          // shows immediately
      await saveCompleted(lesson.id, next);  // server request
      startTransition(() => setCompleted(next)); // confirm
    });
  }

  return (
    <label>
      <input type="checkbox" checked={optimisticCompleted} onChange={handleChange} />
      {lesson.title}
    </label>
  );
}

How it works:

  • useOptimistic(state) returns [optimisticState, setOptimistic]. When no action is pending, optimisticState is state.
  • Inside an action (a transition or form action), calling setOptimistic shows the temporary value immediately.
  • When the action finishes, React drops the optimistic value and shows the real state again. If you updated state (success), the UI keeps the new value. If the request threw and you didn’t update it (failure), the UI automatically rolls back.

You can pass a reducer to combine the current state with an optimistic change — perfect for lists:

JSX
const [optimisticComments, addOptimisticComment] = useOptimistic(
  comments,
  (current, newComment) => [...current, { ...newComment, pending: true }]
);

async function postAction(formData) {
  const text = formData.get('text');
  addOptimisticComment({ id: crypto.randomUUID(), text });
  const saved = await postComment(text);
  startTransition(() => setComments((c) => [...c, saved]));
}

// render: style comments with `pending: true` more faintly
<form action={postAction}>…</form>

Show pending items slightly faded or with a “Sending…” label, so users know they aren’t confirmed yet.

Note: state updates after an await inside a transition need their own startTransition wrapper to be part of the transition — that’s why the examples wrap setCompleted and setComments.

Optimistic updates with TanStack Query

When the data lives in TanStack Query’s cache, update the cache itself optimistically:

JSX
const queryClient = useQueryClient();

const toggleLesson = useMutation({
  mutationFn: ({ id, completed }) => saveCompleted(id, completed),

  onMutate: async ({ id, completed }) => {
    await queryClient.cancelQueries({ queryKey: ['lessons'] });
    const previous = queryClient.getQueryData(['lessons']);
    queryClient.setQueryData(['lessons'], (old) =>
      old.map((l) => (l.id === id ? { ...l, completed } : l))
    );
    return { previous };                       // context for rollback
  },

  onError: (err, variables, context) => {
    queryClient.setQueryData(['lessons'], context.previous);   // roll back
  },

  onSettled: () => {
    queryClient.invalidateQueries({ queryKey: ['lessons'] });  // resync with the server
  },
});
  1. onMutate cancels in-flight refetches (so they don’t overwrite the optimistic data), snapshots the current data and writes the optimistic version.
  2. onError restores the snapshot.
  3. onSettled refetches to make sure the cache matches the server either way.

When not to be optimistic

Optimistic UI suits frequent, low-risk, easily reversible actions. Don’t use it for:

  • payments and purchases,
  • actions that often fail validation on the server,
  • irreversible actions (deleting an account),
  • anything where showing success and then reverting would mislead the user.

For those, show a clear pending state and wait for the server.

Always handle failure. An optimistic update that silently reverts confuses users. Show a short message — “Couldn’t save — please try again” — when you roll back.

Exercise

An optimistic like button

Write LikeButton({ initialLikes, likePost }) using useState for the confirmed count and useOptimistic for the displayed count. On click, start a transition that adds 1 optimistically, awaits likePost() (which returns the new server count) and then stores the confirmed count. If likePost rejects, the count must return to its previous value and an error message “Couldn’t save your like” should appear.

JavaScript
import { useOptimistic, useState, startTransition } from 'react';

export function LikeButton({ initialLikes, likePost }) {
  // your code here
}

Summary

  • useMutation({ mutationFn }) runs create, update and delete requests and tracks their pending and error state.
  • After a mutation succeeds, invalidate related queries so they refetch: queryClient.invalidateQueries({ queryKey }).
  • Optimistic UI shows the expected result immediately and rolls back if the request fails.
  • React’s useOptimistic shows a temporary value while an action is pending, then returns to the real state.
  • TanStack Query can also update the cache optimistically with onMutate, rolling back in onError.