0
Fork 0
mirror of https://github.com/TanStack/query.git synced 2026-11-16 22:50:20 +00:00
query/examples/react/nextjs-app-optimistic-updates
github-actions[bot] c08f5766dd
ci: Version Packages (#11511)
ci: changeset release

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
History 2026-09-16 16:56:55 +02:00
..
app chore(examples,docs): replace deprecated 'prefetchQuery'/'fetchQuery' calls with 'query' (#11282) 2026-08-25 15:06:52 +09:00
components docs(examples): add Next.js App Router optimistic updates example (#10997) 2026-08-18 09:57:04 +02:00
.gitignore docs(examples): add Next.js App Router optimistic updates example (#10997) 2026-08-18 09:57:04 +02:00
next.config.js docs(examples): add Next.js App Router optimistic updates example (#10997) 2026-08-18 09:57:04 +02:00
package.json ci: Version Packages (#11511) 2026-09-16 16:56:55 +02:00
README.md docs(examples): add Next.js App Router optimistic updates example (#10997) 2026-08-18 09:57:04 +02:00
tsconfig.json docs(examples): add Next.js App Router optimistic updates example (#10997) 2026-08-18 09:57:04 +02:00

TanStack Query — Next.js App Router Optimistic Updates

This example demonstrates optimistic updates with TanStack Query v5 in a Next.js 14 App Router project.

What it shows

A todo list where items appear in the UI immediately after submission — before the server confirms. The server randomly fails ~30% of the time so you can observe automatic rollback behaviour.

Two approaches are shown side by side via a tab toggle:

Approach 1 — Via UI Variables (simpler)

Render the pending item directly from mutation.variables. No cache touching required. On error, the pending item simply disappears and an error message is shown.

const mutation = useMutation({ mutationFn: addTodo, onSettled: invalidate })

// In JSX:
{mutation.isPending && <li style={{ opacity: 0.5 }}>{mutation.variables}</li>}

Best when: the mutation input maps 1-to-1 to what you'd show while pending.

Approach 2 — Via Cache Manipulation (onMutate + rollback)

onMutate cancels in-flight refetches, snapshots the current cache, and writes an optimistic item directly into the cache. onError restores the snapshot.

const mutation = useMutation({
  mutationFn: addTodo,
  onMutate: async (text) => {
    await queryClient.cancelQueries({ queryKey: ['todos'] })
    const previousTodos = queryClient.getQueryData<Todo[]>(['todos'])
    queryClient.setQueryData<Todo[]>(['todos'], (old = []) => [
      ...old,
      optimistic,
    ])
    return { previousTodos }
  },
  onError: (_err, _vars, context) => {
    queryClient.setQueryData(['todos'], context?.previousTodos)
  },
  onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
})

Best when: you need fine-grained control or the optimistic shape differs from mutation.variables.

Running the example

npm install
npm run dev

Open http://localhost:3000.

Learn more