-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
feat(examples): add Next.js App Router optimistic updates example #10997
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
TkDodo
merged 7 commits into
TanStack:main
from
guirab:feat/nextjs-app-optimistic-updates
Aug 18, 2026
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
00a4652
feat(examples): add Next.js App Router optimistic updates example
7ad24c1
refactor(examples/nextjs-app-optimistic-updates): apply post-review cβ¦
083bcda
refactor(examples/nextjs-app-optimistic-updates): apply post-review cβ¦
273db38
Merge branch 'main' into feat/nextjs-app-optimistic-updates
TkDodo 17f9bbf
update deps
TkDodo 8f010b7
ref: remove other optimistic update examples
TkDodo f40a0b5
ci: apply automated fixes
autofix-ci[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| # 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. | ||
|
|
||
| ```ts | ||
| 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. | ||
|
|
||
| ```ts | ||
| 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 | ||
|
|
||
| ```bash | ||
| npm install | ||
| npm run dev | ||
| ``` | ||
|
|
||
| Open [http://localhost:3000](http://localhost:3000). | ||
|
|
||
| ## Learn more | ||
|
|
||
| - [TanStack Query β Optimistic Updates](https://tanstack.com/query/latest/docs/framework/react/guides/optimistic-updates) | ||
| - [Next.js App Router](https://nextjs.org/docs/app) |
28 changes: 28 additions & 0 deletions
28
examples/react/nextjs-app-optimistic-updates/app/api/todos/data.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| export interface Todo { | ||
| id: string | ||
| text: string | ||
| createdAt: number | ||
| } | ||
|
|
||
| export const todos: Array<Todo> = [ | ||
| { | ||
| id: crypto.randomUUID(), | ||
| text: 'Buy groceries', | ||
| createdAt: Date.now() - 3000, | ||
| }, | ||
| { | ||
| id: crypto.randomUUID(), | ||
| text: 'Walk the dog', | ||
| createdAt: Date.now() - 2000, | ||
| }, | ||
| { | ||
| id: crypto.randomUUID(), | ||
| text: 'Read a book', | ||
| createdAt: Date.now() - 1000, | ||
| }, | ||
| ] | ||
|
|
||
| export async function getTodos(): Promise<Array<Todo>> { | ||
| await new Promise((resolve) => setTimeout(resolve, 200)) | ||
| return todos | ||
| } |
46 changes: 46 additions & 0 deletions
46
examples/react/nextjs-app-optimistic-updates/app/api/todos/route.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| import { NextResponse } from 'next/server' | ||
| import { todos, getTodos, type Todo } from './data' | ||
|
|
||
| export async function GET() { | ||
| return NextResponse.json(await getTodos()) | ||
| } | ||
|
|
||
| export async function POST(request: Request) { | ||
| let body: unknown | ||
| try { | ||
| body = await request.json() | ||
| } catch { | ||
| return NextResponse.json({ error: 'text is required' }, { status: 400 }) | ||
| } | ||
|
|
||
| const text = | ||
| body !== null && | ||
| typeof body === 'object' && | ||
| 'text' in body && | ||
| typeof (body as { text: unknown }).text === 'string' | ||
| ? (body as { text: string }).text.trim() | ||
| : '' | ||
|
|
||
| if (!text) { | ||
| return NextResponse.json({ error: 'text is required' }, { status: 400 }) | ||
| } | ||
|
|
||
| await new Promise((resolve) => setTimeout(resolve, 500)) | ||
|
|
||
| if (Math.random() < 0.3) { | ||
| return NextResponse.json( | ||
| { error: 'Server error β please try again' }, | ||
| { status: 500 }, | ||
| ) | ||
| } | ||
|
|
||
| const newTodo: Todo = { | ||
| id: crypto.randomUUID(), | ||
| text, | ||
| createdAt: Date.now(), | ||
| } | ||
|
|
||
| todos.push(newTodo) | ||
|
|
||
| return NextResponse.json(newTodo, { status: 201 }) | ||
| } | ||
31 changes: 31 additions & 0 deletions
31
examples/react/nextjs-app-optimistic-updates/app/get-query-client.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| import { | ||
| QueryClient, | ||
| defaultShouldDehydrateQuery, | ||
| environmentManager, | ||
| } from '@tanstack/react-query' | ||
|
|
||
| function makeQueryClient() { | ||
| return new QueryClient({ | ||
| defaultOptions: { | ||
| queries: { | ||
| staleTime: 60 * 1000, | ||
| }, | ||
| dehydrate: { | ||
| shouldDehydrateQuery: (query) => | ||
| defaultShouldDehydrateQuery(query) || | ||
| query.state.status === 'pending', | ||
| }, | ||
| }, | ||
| }) | ||
| } | ||
|
|
||
| let browserQueryClient: QueryClient | undefined = undefined | ||
|
|
||
| export function getQueryClient() { | ||
| if (environmentManager.isServer()) { | ||
| return makeQueryClient() | ||
| } else { | ||
| if (!browserQueryClient) browserQueryClient = makeQueryClient() | ||
| return browserQueryClient | ||
| } | ||
| } |
22 changes: 22 additions & 0 deletions
22
examples/react/nextjs-app-optimistic-updates/app/layout.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| import Providers from './providers' | ||
| import type React from 'react' | ||
| import type { Metadata } from 'next' | ||
|
|
||
| export const metadata: Metadata = { | ||
| title: 'TanStack Query β Optimistic Updates', | ||
| description: 'Next.js App Router example with optimistic updates', | ||
| } | ||
|
|
||
| export default function RootLayout({ | ||
| children, | ||
| }: { | ||
| children: React.ReactNode | ||
| }) { | ||
| return ( | ||
| <html lang="en"> | ||
| <body> | ||
| <Providers>{children}</Providers> | ||
| </body> | ||
| </html> | ||
| ) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| import React from 'react' | ||
| import { HydrationBoundary, dehydrate } from '@tanstack/react-query' | ||
| import { getQueryClient } from '@/app/get-query-client' | ||
| import { getTodos } from '@/app/api/todos/data' | ||
| import ApproachTabs from '@/components/ApproachTabs' | ||
|
|
||
| export default function Home() { | ||
| const queryClient = getQueryClient() | ||
|
|
||
| void queryClient.prefetchQuery({ | ||
| queryKey: ['todos'], | ||
| queryFn: getTodos, | ||
| }) | ||
|
|
||
| return ( | ||
| <main style={{ maxWidth: 600, margin: '0 auto', padding: '2rem 1rem' }}> | ||
| <h1>Optimistic Updates with TanStack Query</h1> | ||
| <p style={{ color: '#666', marginBottom: '1.5rem' }}> | ||
| Add todos to see optimistic updates in action. The server randomly fails | ||
| ~30% of the time so you can observe automatic rollback. | ||
| </p> | ||
| <HydrationBoundary state={dehydrate(queryClient)}> | ||
| <ApproachTabs /> | ||
| </HydrationBoundary> | ||
| </main> | ||
| ) | ||
| } |
16 changes: 16 additions & 0 deletions
16
examples/react/nextjs-app-optimistic-updates/app/providers.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| 'use client' | ||
| import { QueryClientProvider } from '@tanstack/react-query' | ||
| import { ReactQueryDevtools } from '@tanstack/react-query-devtools' | ||
| import { getQueryClient } from '@/app/get-query-client' | ||
| import type * as React from 'react' | ||
|
|
||
| export default function Providers({ children }: { children: React.ReactNode }) { | ||
| const queryClient = getQueryClient() | ||
|
|
||
| return ( | ||
| <QueryClientProvider client={queryClient}> | ||
| {children} | ||
| <ReactQueryDevtools /> | ||
| </QueryClientProvider> | ||
| ) | ||
| } |
46 changes: 46 additions & 0 deletions
46
examples/react/nextjs-app-optimistic-updates/components/ApproachTabs.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| 'use client' | ||
|
|
||
| import React, { useState } from 'react' | ||
| import TodoListUI from './TodoListUI' | ||
| import TodoListCache from './TodoListCache' | ||
|
|
||
| type Tab = 'ui-variables' | 'cache' | ||
|
|
||
| export default function ApproachTabs() { | ||
| const [activeTab, setActiveTab] = useState<Tab>('ui-variables') | ||
|
|
||
| const tabStyle = (tab: Tab): React.CSSProperties => ({ | ||
| padding: '0.5rem 1rem', | ||
| border: 'none', | ||
| borderBottom: | ||
| activeTab === tab ? '2px solid #0070f3' : '2px solid transparent', | ||
| background: 'none', | ||
| cursor: 'pointer', | ||
| fontWeight: activeTab === tab ? 600 : 400, | ||
| color: activeTab === tab ? '#0070f3' : '#555', | ||
| }) | ||
|
|
||
| return ( | ||
| <div> | ||
| <div | ||
| style={{ | ||
| display: 'flex', | ||
| borderBottom: '1px solid #ddd', | ||
| marginBottom: '1.5rem', | ||
| }} | ||
| > | ||
| <button | ||
| style={tabStyle('ui-variables')} | ||
| onClick={() => setActiveTab('ui-variables')} | ||
| > | ||
| Via UI Variables | ||
| </button> | ||
| <button style={tabStyle('cache')} onClick={() => setActiveTab('cache')}> | ||
| Via Cache Manipulation | ||
| </button> | ||
| </div> | ||
|
|
||
| {activeTab === 'ui-variables' ? <TodoListUI /> : <TodoListCache />} | ||
| </div> | ||
| ) | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.