examples/react/hydration-nextjs-pages-router
| Name | Last commit message | Last commit date |
|---|---|---|
| .. | ||
README.md
TanStack React Query Hydration Example (Next.js Pages Router)#
Prefetches posts in getStaticProps, dehydrates the cache, and hydrates it in the browser with HydrationBoundary.
Built with Next.js (Pages Router).
How it works#
src/services/posts/queries.tsdefinespostsQueries.list(limit)withqueryOptions, keyed by['posts', 'list', limit].src/services/posts/api.tsfetches the posts from JSONPlaceholder and keeps the firstlimitof them.src/pages/index.tsxrunsqueryClient.query(postsQueries.list(10))on a freshQueryClientingetStaticPropsand returnsdehydrate(queryClient)asdehydratedState.src/pages/_app.tsxpassespageProps.dehydratedStatetoHydrationBoundary, and itsQueryClientsets astaleTimeof 1 minute, so the prefetched list is not refetched on mount while it is less than a minute old. Hydration keeps the time the data was fetched ingetStaticProps, so a page served later than that refetches.src/components/PostList.tsxreadsuseQuery(postsQueries.list(postCount)), and "Show More" raisespostCountby 10, which fetches a new list. Onsrc/pages/client-only.tsxthe same component runs without prefetching, so the first list is fetched in the browser.
To run this example:
npm installnpm run dev