examples/react/prefetching-nextjs-pages-router
| Name | Last commit message | Last commit date |
|---|---|---|
| .. | ||
README.md
TanStack React Query Prefetching Example (Next.js Pages Router)#
Prefetches a character when you hover its link, so the detail view opens without a loading state.
Built with Next.js (Pages Router).
How it works#
src/services/characters/queries.tsdefinescharactersQueries.list()andcharactersQueries.detail(id)withqueryOptions. The detailqueryFnisskipTokenwhenidisundefined.src/services/characters/api.tswaits 500 ms before each request to the Rick and Morty API.- In
src/pages/index.tsx, eachCharacterItemcallsqueryClient.query({ ...charactersQueries.detail(char.id), staleTime: 10 * 1000 })ononMouseEnterandonFocus, so a character is fetched only if it is missing or older than 10 seconds. It also observes the detail withuseQueryandenabled: falseto bold characters that are already cached. - The selected character in
src/pages/index.tsxis read withuseQuery(charactersQueries.detail(selectedChar)), so clicking a prefetched character shows it immediately. src/pages/character/[id].tsxreads the same detail options withuseQuery, passingundefinedfor an invalid id, and renders prefetched characters without a loading state.
To run this example:
npm installnpm run dev