Open History to see the last commit
1# TanStack Query β Next.js App Router Optimistic Updates
2β
3This example demonstrates **optimistic updates** with TanStack Query v5 in a Next.js 14 App Router project.
4β
5## What it shows
6β
7A 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.
8β
9Two approaches are shown side by side via a tab toggle:
10β
11### Approach 1 β Via UI Variables (simpler)
12β
13Render the pending item directly from `mutation.variables`. No cache touching required. On error, the pending item simply disappears and an error message is shown.
14β
15```ts
16const mutation = useMutation({ mutationFn: addTodo, onSettled: invalidate })
17β
18// In JSX:
19{mutation.isPending && <li style={{ opacity: 0.5 }}>{mutation.variables}</li>}
20```
21β
22**Best when:** the mutation input maps 1-to-1 to what you'd show while pending.
23β
24### Approach 2 β Via Cache Manipulation (`onMutate` + rollback)
25β
26`onMutate` cancels in-flight refetches, snapshots the current cache, and writes an optimistic item directly into the cache. `onError` restores the snapshot.
27β
28```ts
29const mutation = useMutation({
30 mutationFn: addTodo,
31 onMutate: async (text) => {
32 await queryClient.cancelQueries({ queryKey: ['todos'] })
33 const previousTodos = queryClient.getQueryData<Todo[]>(['todos'])
34 queryClient.setQueryData<Todo[]>(['todos'], (old = []) => [
35 ...old,
36 optimistic,
37 ])
38 return { previousTodos }
39 },
40 onError: (_err, _vars, context) => {
41 queryClient.setQueryData(['todos'], context?.previousTodos)
42 },
43 onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
44})
45```
46β
47**Best when:** you need fine-grained control or the optimistic shape differs from `mutation.variables`.
48β
49## Running the example
50β
51```bash
52npm install
53npm run dev
54```
55β
56Open [http://localhost:3000](http://localhost:3000).
57β
58## Learn more
59β
60- [TanStack Query β Optimistic Updates](https://tanstack.com/query/latest/docs/framework/react/guides/optimistic-updates)
61- [Next.js App Router](https://nextjs.org/docs/app)