0
Fork 0
mirror of https://github.com/TanStack/query.git synced 2026-11-18 19:33:22 +00:00
query/examples/react/nextjs-app-optimistic-updates
Wonsuk Choi 92c41c0594
refactor(examples/react/nextjs-app-optimistic-updates): type the form submit handlers with 'React.SubmitEvent' instead of the deprecated 'React.FormEvent' (#12095)
* refactor(examples/react/nextjs-app-optimistic-updates): type the form submit handlers with 'React.SubmitEvent' instead of the deprecated 'React.FormEvent'

* chore(examples/react/nextjs-app-optimistic-updates/package.json): raise the '@types/react' minimum to '^19.2.10' for 'React.SubmitEvent'
History 2026-11-01 22:35:41 +09:00
..
app refactor(examples/react/{nextjs-app-optimistic-updates,nextjs-app-prefetching}): move the data layer into 'services/{domain}' with a query factory (#12356) 2026-10-26 00:11:30 +09:00
components refactor(examples/react/nextjs-app-optimistic-updates): type the form submit handlers with 'React.SubmitEvent' instead of the deprecated 'React.FormEvent' (#12095) 2026-11-01 22:35:41 +09:00
services/todos refactor(examples/react/{nextjs-app-optimistic-updates,nextjs-app-prefetching}): move the data layer into 'services/{domain}' with a query factory (#12356) 2026-10-26 00:11:30 +09:00
.gitignore docs(examples): add Next.js App Router optimistic updates example (#10997) 2026-08-18 09:57:04 +02:00
eslint.config.js chore(examples/*/eslint.config): use 'flat/recommended-strict' from '@tanstack/eslint-plugin-query' (#12385) 2026-10-26 02:55:51 +09: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 (#12391) 2026-11-01 11:04:19 +01:00
README.md docs(*): use American spellings 'behavior', 'initialized', and 'optimize', and 'falsy' instead of 'falsey' (#12348) 2026-10-25 21:27:53 +09:00
tsconfig.json chore(examples/*/tsconfig): include '*.config.ts' and '*.config.js' like the packages (#12408) 2026-10-27 09:11:08 +09: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 behavior.

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