Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

README.md

17 lines1.1 KB

1# TanStack React Query Prefetching Example (Next.js App Router)
2​
3Prefetches a Pokémon in a Server Component and hydrates it in a Client Component with `HydrationBoundary`.
4​
5Built with [Next.js (App Router)](https://nextjs.org/docs/app).
6​
7## How it works
8​
9- `services/pokemons/queries.ts` defines `pokemonsQueries.detail(id)` with `queryOptions`, and `services/pokemons/api.ts` fetches the Pokémon from PokéAPI.
10- `app/get-query-client.ts` creates a new `QueryClient` per request on the server and reuses one in the browser. Its `dehydrate` defaults include pending queries through `shouldDehydrateQuery` and turn off `shouldRedactErrors`.
11- `app/page.tsx` is a Server Component that starts `queryClient.query(pokemonsQueries.detail(25))` without awaiting it and passes `dehydrate(queryClient)` to `HydrationBoundary`, so the pending query is sent to the client.
12- `app/pokemon-info.tsx` is a Client Component that reads the same options with `useSuspenseQuery` and picks up the data streamed from the server instead of fetching again.
13​
14To run this example:
15​
16- `npm install`
17- `npm run dev`