From df8bbf217fd29e968fa94fd65cc7f7ede2b2c433 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ciar=C3=A1n=20Curley?= Date: Tue, 6 Oct 2026 16:59:20 +0100 Subject: [PATCH] docs: use new query methods (#7100) docs: use queryClient.query() in guides and agent skills Co-authored-by: Claude Opus 5.5 (1M context) --- _artifacts/domain_map.yaml | 16 ++--- _artifacts/skill_spec.md | 10 +-- _artifacts/skill_tree.yaml | 2 +- .../eslint/create-route-property-order.md | 20 ++++-- docs/router/guide/deferred-data-loading.md | 10 +-- docs/router/guide/external-data-loading.md | 6 +- docs/router/guide/router-context.md | 3 +- docs/router/guide/type-safety.md | 13 ++-- docs/router/how-to/setup-testing.md | 3 +- docs/router/integrations/query.md | 24 ++++--- .../react/guide/deferred-hydration.md | 8 ++- .../react/guide/server-components.md | 5 +- .../skills/compositions/router-query/SKILL.md | 63 ++++++++++++------- .../react-start/server-components/SKILL.md | 4 +- .../docs/caching-refresh-ssr.md | 7 ++- .../examples/03-query-owned-rsc.tsx | 7 ++- .../skills/router-core/type-safety/SKILL.md | 10 +-- 17 files changed, 136 insertions(+), 75 deletions(-) diff --git a/_artifacts/domain_map.yaml b/_artifacts/domain_map.yaml index 4b5d6f8386..0b2672f0c6 100644 --- a/_artifacts/domain_map.yaml +++ b/_artifacts/domain_map.yaml @@ -147,13 +147,15 @@ skills: context types to not flow into loader. wrong_pattern: | createFileRoute('/posts')({ - loader: ({ context }) => context.queryClient.ensureQueryData(postsQuery), + loader: ({ context }) => + context.queryClient.query({ ...postsQuery, staleTime: 'static' }), beforeLoad: ({ context }) => ({ queryClient: context.queryClient }), }) correct_pattern: | createFileRoute('/posts')({ beforeLoad: ({ context }) => ({ queryClient: context.queryClient }), - loader: ({ context }) => context.queryClient.ensureQueryData(postsQuery), + loader: ({ context }) => + context.queryClient.query({ ...postsQuery, staleTime: 'static' }), }) source: 'docs/router/eslint/create-route-property-order.md' priority: HIGH @@ -536,7 +538,7 @@ skills: - '@tanstack/react-router-ssr-query' covers: - External cache coordination pattern - - queryClient.ensureQueryData in loader + - "queryClient.query with staleTime: 'static' in loader" - useSuspenseQuery in components - setupRouterSsrQueryIntegration - defaultPreloadStaleTime @@ -579,11 +581,11 @@ skills: priority: HIGH status: active - - mistake: 'Awaiting prefetchQuery in loader blocks rendering' + - mistake: 'Awaiting a fire-and-forget query in loader blocks rendering' mechanism: >- - For streaming/deferred patterns, prefetchQuery should NOT - be awaited in the loader — it starts fetching on server - and streams without blocking. Awaiting defeats the purpose. + For streaming/deferred patterns, start a query without awaiting + it and handle failures with catch(noop) — it starts fetching on + the server and streams without blocking. Awaiting defeats the purpose. source: 'docs/router/integrations/query.md' priority: MEDIUM status: active diff --git a/_artifacts/skill_spec.md b/_artifacts/skill_spec.md index 4503afb48a..7eb9554a42 100644 --- a/_artifacts/skill_spec.md +++ b/_artifacts/skill_spec.md @@ -83,11 +83,11 @@ TanStack Router is a type-safe router for React and Solid applications with buil ### external-data-loading (3 failure modes) -| # | Mistake | Priority | Source | Cross-skill? | -| --- | ------------------------------------------------- | -------- | -------------------------------- | ------------ | -| 1 | Not setting defaultPreloadStaleTime to 0 | HIGH | docs/guide/external-data-loading | — | -| 2 | Creating QueryClient outside createRouter for SSR | HIGH | docs/guide/external-data-loading | — | -| 3 | Awaiting prefetchQuery in loader blocks rendering | MEDIUM | docs/integrations/query | — | +| # | Mistake | Priority | Source | Cross-skill? | +| --- | ----------------------------------------------------------- | -------- | -------------------------------- | ------------ | +| 1 | Not setting defaultPreloadStaleTime to 0 | HIGH | docs/guide/external-data-loading | — | +| 2 | Creating QueryClient outside createRouter for SSR | HIGH | docs/guide/external-data-loading | — | +| 3 | Awaiting a fire-and-forget query in loader blocks rendering | MEDIUM | docs/integrations/query | — | ### auth-and-guards (3 failure modes) diff --git a/_artifacts/skill_tree.yaml b/_artifacts/skill_tree.yaml index ec38a04bdd..6f7c4c8742 100644 --- a/_artifacts/skill_tree.yaml +++ b/_artifacts/skill_tree.yaml @@ -246,7 +246,7 @@ skills: package: 'packages/react-router' description: >- Integrating TanStack Router with TanStack Query: queryClient - in router context, ensureQueryData/prefetchQuery in loaders, + in router context, static queries and fire-and-forget queries in loaders, useSuspenseQuery in components, defaultPreloadStaleTime: 0, setupRouterSsrQueryIntegration for SSR dehydration/hydration and streaming, per-request QueryClient isolation. diff --git a/docs/router/eslint/create-route-property-order.md b/docs/router/eslint/create-route-property-order.md index c22aa7c52d..453fd64acc 100644 --- a/docs/router/eslint/create-route-property-order.md +++ b/docs/router/eslint/create-route-property-order.md @@ -37,7 +37,10 @@ import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/path')({ loader: async ({ context }) => { - await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) + await context.queryClient.query({ + ...getQueryOptions(context.hello), + staleTime: 'static', + }) }, beforeLoad: () => ({ hello: 'world' }), }) @@ -55,7 +58,10 @@ import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/path')({ loader: async ({ context }) => { - await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) + await context.queryClient.query({ + ...getQueryOptions(context.hello), + staleTime: 'static', + }) }, beforeLoad: () => ({ hello: 'world' }), }) @@ -80,7 +86,10 @@ import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/path')({ beforeLoad: () => ({ hello: 'world' }), loader: async ({ context }) => { - await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) + await context.queryClient.query({ + ...getQueryOptions(context.hello), + staleTime: 'static', + }) }, }) ``` @@ -98,7 +107,10 @@ import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/path')({ beforeLoad: () => ({ hello: 'world' }), loader: async ({ context }) => { - await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) + await context.queryClient.query({ + ...getQueryOptions(context.hello), + staleTime: 'static', + }) }, }) ``` diff --git a/docs/router/guide/deferred-data-loading.md b/docs/router/guide/deferred-data-loading.md index 9956542ebd..f378d7adbf 100644 --- a/docs/router/guide/deferred-data-loading.md +++ b/docs/router/guide/deferred-data-loading.md @@ -90,15 +90,16 @@ So, instead of using `defer` and `Await`, you'll instead want to use the Route's ```tsx // src/routes/posts.$postId.tsx import { createFileRoute } from '@tanstack/react-router' +import { noop } from '@tanstack/react-query' import { slowDataOptions, fastDataOptions } from '~/api/query-options' export const Route = createFileRoute('/posts/$postId')({ loader: async ({ context: { queryClient } }) => { // Kick off the fetching of some slower data, but do not await it - queryClient.prefetchQuery(slowDataOptions()) + void queryClient.query(slowDataOptions()).catch(noop) // Fetch and await some data that resolves quickly - await queryClient.ensureQueryData(fastDataOptions()) + await queryClient.query({ ...fastDataOptions(), staleTime: 'static' }) }, }) ``` @@ -108,15 +109,16 @@ export const Route = createFileRoute('/posts/$postId')({ ```tsx // src/routes/posts.$postId.tsx import { createFileRoute } from '@tanstack/solid-router' +import { noop } from '@tanstack/solid-query' import { slowDataOptions, fastDataOptions } from '~/api/query-options' export const Route = createFileRoute('/posts/$postId')({ loader: async ({ context: { queryClient } }) => { // Kick off the fetching of some slower data, but do not await it - queryClient.prefetchQuery(slowDataOptions()) + void queryClient.query(slowDataOptions()).catch(noop) // Fetch and await some data that resolves quickly - await queryClient.ensureQueryData(fastDataOptions()) + await queryClient.query({ ...fastDataOptions(), staleTime: 'static' }) }, }) ``` diff --git a/docs/router/guide/external-data-loading.md b/docs/router/guide/external-data-loading.md index c044db7757..664468752d 100644 --- a/docs/router/guide/external-data-loading.md +++ b/docs/router/guide/external-data-loading.md @@ -84,7 +84,8 @@ const postsQueryOptions = queryOptions({ export const Route = createFileRoute('/posts')({ // Use the `loader` option to ensure that the data is loaded - loader: () => queryClient.ensureQueryData(postsQueryOptions), + loader: () => + queryClient.query({ ...postsQueryOptions, staleTime: 'static' }), component: () => { // Read the data from the cache and subscribe to updates const { @@ -108,7 +109,8 @@ When an error occurs while using `suspense` with `TanStack Query`, you need to l ```tsx export const Route = createFileRoute('/')({ - loader: () => queryClient.ensureQueryData(postsQueryOptions), + loader: () => + queryClient.query({ ...postsQueryOptions, staleTime: 'static' }), errorComponent: ({ error, reset }) => { const router = useRouter() const queryErrorResetBoundary = useQueryErrorResetBoundary() diff --git a/docs/router/guide/router-context.md b/docs/router/guide/router-context.md index 5fc4001010..347082106f 100644 --- a/docs/router/guide/router-context.md +++ b/docs/router/guide/router-context.md @@ -278,9 +278,10 @@ Then, in your route: export const Route = createFileRoute('/todos')({ component: Todos, loader: async ({ context }) => { - await context.queryClient.ensureQueryData({ + await context.queryClient.query({ queryKey: ['todos', { userId: user.id }], queryFn: fetchTodos, + staleTime: 'static', }) }, }) diff --git a/docs/router/guide/type-safety.md b/docs/router/guide/type-safety.md index 2adffc58c5..3faaed79e7 100644 --- a/docs/router/guide/type-safety.md +++ b/docs/router/guide/type-safety.md @@ -137,12 +137,13 @@ As your application scales, TypeScript check times will naturally increase. Ther ### Only infer types you need -A great pattern with client side data caches (TanStack Query, etc.) is to prefetch data. For example with TanStack Query you might have a route which calls `queryClient.ensureQueryData` in a `loader`. +A great pattern with client side data caches (TanStack Query, etc.) is to prefetch data. For example with TanStack Query you might have a route which calls `queryClient.query` in a `loader`. ```tsx export const Route = createFileRoute('/posts/$postId/deep')({ + // (ctx: LoaderFnContext) => Promise loader: ({ context: { queryClient }, params: { postId } }) => - queryClient.ensureQueryData(postQueryOptions(postId)), + queryClient.query({ ...postQueryOptions(postId), staleTime: 'static' }), component: PostDeepComponent, }) @@ -154,12 +155,16 @@ function PostDeepComponent() { } ``` -This may look fine and for small route trees and you may not notice any TS performance issues. However in this case TS has to infer the loader's return type, despite it never being used in your route. If the loader data is a complex type with many routes that prefetch in this manner, it can slow down editor performance. In this case, the change is quite simple and let typescript infer Promise. +This may look fine and for small route trees and you may not notice any TS performance issues. However in this case TS has to infer the loader's return type, despite it never being used in your route. If the loader data is a complex type with many routes that prefetch in this manner, it can slow down editor performance. In this case, the change is quite simple and let typescript infer `Promise`. ```tsx export const Route = createFileRoute('/posts/$postId/deep')({ + // (ctx: LoaderFnContext) => Promise loader: async ({ context: { queryClient }, params: { postId } }) => { - await queryClient.ensureQueryData(postQueryOptions(postId)) + await queryClient.query({ + ...postQueryOptions(postId), + staleTime: 'static', + }) }, component: PostDeepComponent, }) diff --git a/docs/router/how-to/setup-testing.md b/docs/router/how-to/setup-testing.md index 48afa122f4..104cbedc0d 100644 --- a/docs/router/how-to/setup-testing.md +++ b/docs/router/how-to/setup-testing.md @@ -659,9 +659,10 @@ describe('React Query Integration', () => { path: '/posts', component: PostsList, loader: ({ context: { queryClient } }) => - queryClient.ensureQueryData({ + queryClient.query({ queryKey: ['posts'], queryFn: mockFetchPosts, + staleTime: 'static', }), }) diff --git a/docs/router/integrations/query.md b/docs/router/integrations/query.md index fd174187b5..707f90900c 100644 --- a/docs/router/integrations/query.md +++ b/docs/router/integrations/query.md @@ -152,7 +152,7 @@ Preload critical data in the route `loader` to avoid waterfalls and loading flas -# React +# Blocking `query` in loader ```tsx title="src/routes/posts.tsx" import { queryOptions, useSuspenseQuery, useQuery } from '@tanstack/react-query' @@ -165,7 +165,12 @@ const postsQuery = queryOptions({ export const Route = createFileRoute('/posts')({ // Ensure the data is in the cache before render - loader: ({ context }) => context.queryClient.ensureQueryData(postsQuery), + loader: ({ context }) => + context.queryClient.query({ + ...postsQuery, + // returns data from cache immediately, otherwise executes a fetch + staleTime: 'static', + }), component: PostsPage, }) @@ -180,15 +185,15 @@ function PostsPage() { ### Prefetching and streaming -You can also prefetch with `fetchQuery` or `ensureQueryData` in a loader without consuming the data in a component. If you return the promise directly from the loader, it will be awaited and thus block the SSR request until the query finishes. If you don't await the promise nor return it, the query will be started on the server and will be streamed to the client without blocking the SSR request. +You can also prefetch with `query` in a loader without consuming the data in a component. If you return the promise directly from the loader, it will be awaited and thus block the SSR request until the query finishes. If you don't await the promise nor return it, the query will be started on the server and will be streamed to the client without blocking the SSR request. -# React +# Non-blocking `query` in loader ```tsx title="src/routes/users.$id.tsx" import { createFileRoute } from '@tanstack/react-router' -import { queryOptions, useQuery } from '@tanstack/react-query' +import { noop, queryOptions, useQuery } from '@tanstack/react-query' const userQuery = (id: string) => queryOptions({ @@ -197,15 +202,18 @@ const userQuery = (id: string) => }) export const Route = createFileRoute('/user/$id')({ - loader: ({ params }) => { - // do not await this nor return the promise, just kick off the query to stream it to the client - context.queryClient.fetchQuery(userQuery(params.id)) + loader: ({ context, params }) => { + // Do not await this nor return the promise, just kick off the query to stream it to the client + void context.queryClient.query(userQuery(params.id)).catch(noop) }, }) ``` +> [!NOTE] +> Previous versions of this guide used `queryClient.ensureQueryData` and `queryClient.prefetchQuery`. These methods are now deprecated in TanStack Query in favor of `queryClient.query`. See the TanStack Query [v5 migration guide](https://tanstack.com/query/latest/docs/framework/react/guides/migrating-to-v5#imperative-queryclient-methods) for more details. + ## Redirect handling If a query or mutation throws a `redirect(...)`, the integration intercepts it on the client and performs a router navigation. diff --git a/docs/start/framework/react/guide/deferred-hydration.md b/docs/start/framework/react/guide/deferred-hydration.md index 1dc4760fa7..ba07d65b24 100644 --- a/docs/start/framework/react/guide/deferred-hydration.md +++ b/docs/start/framework/react/guide/deferred-hydration.md @@ -244,7 +244,7 @@ chunks only exist when `split` is enabled, so TypeScript rejects strategy-form Use procedural prefetch when you need custom work: ```tsx -import { useQueryClient } from '@tanstack/react-query' +import { noop, useQueryClient } from '@tanstack/react-query' import { Hydrate } from '@tanstack/react-start' import { visible } from '@tanstack/react-start/hydration' @@ -255,8 +255,10 @@ function DeferredReviews() { { - await preload() - await queryClient.prefetchQuery(reviewsQueryOptions) + await Promise.all([ + preload(), + queryClient.query(reviewsQueryOptions).catch(noop), + ]) }} > diff --git a/docs/start/framework/react/guide/server-components.md b/docs/start/framework/react/guide/server-components.md index 6bbc716754..356c901dee 100644 --- a/docs/start/framework/react/guide/server-components.md +++ b/docs/start/framework/react/guide/server-components.md @@ -401,7 +401,10 @@ const postQueryOptions = (postId: string) => ({ export const Route = createFileRoute('/posts/$postId')({ loader: async ({ context, params }) => { // Prefetch during SSR - data reused on client without refetch - await context.queryClient.ensureQueryData(postQueryOptions(params.postId)) + await context.queryClient.query({ + ...postQueryOptions(params.postId), + staleTime: 'static', + }) }, component: PostPage, }) diff --git a/packages/react-router/skills/compositions/router-query/SKILL.md b/packages/react-router/skills/compositions/router-query/SKILL.md index 9bda851b1c..ce634b5068 100644 --- a/packages/react-router/skills/compositions/router-query/SKILL.md +++ b/packages/react-router/skills/compositions/router-query/SKILL.md @@ -2,7 +2,7 @@ name: router-query description: >- Integrating TanStack Router with TanStack Query: queryClient - in router context, ensureQueryData/prefetchQuery in loaders, + in router context, static queries and fire-and-forget queries in loaders, useSuspenseQuery in components, defaultPreloadStaleTime: 0, setupRouterSsrQueryIntegration for SSR dehydration/hydration and streaming, per-request QueryClient isolation. @@ -182,9 +182,9 @@ export function createAppRouter() { } ``` -## Core Pattern: `ensureQueryData` in Loader + `useSuspenseQuery` in Component +## Core Pattern: Static `query` in Loader + `useSuspenseQuery` in Component -This is the recommended pattern. The loader ensures data is in the cache before render (no loading flash). The component subscribes to the cache for updates. +This is the recommended pattern. The loader queries data before render (no loading flash), using `staleTime: 'static'` to reuse cached data without a stale refetch. The component subscribes to the cache for updates. ```tsx // src/routes/posts.tsx @@ -204,9 +204,12 @@ const postsQueryOptions = queryOptions({ export const Route = createFileRoute('/posts')({ loader: ({ context }) => { - // ensureQueryData returns cached data if available, fetches if not in cache - // To also refetch stale data, pass revalidateIfStale: true - return context.queryClient.ensureQueryData(postsQueryOptions) + // query returns cached data when available and fetches when it is missing + // Keep this query static so a stale refetch does not block navigation + return context.queryClient.query({ + ...postsQueryOptions, + staleTime: 'static', + }) }, component: PostsPage, }) @@ -246,7 +249,10 @@ const postQueryOptions = (postId: string) => export const Route = createFileRoute('/posts/$postId')({ loader: ({ context, params }) => { - return context.queryClient.ensureQueryData(postQueryOptions(params.postId)) + return context.queryClient.query({ + ...postQueryOptions(params.postId), + staleTime: 'static', + }) }, component: PostPage, }) @@ -259,20 +265,23 @@ function PostPage() { } ``` -## Streaming Pattern: `prefetchQuery` (Not Awaited) +## Streaming Pattern: Fire-and-Forget `query` (Not Awaited) -For non-critical data, start the fetch without blocking navigation: +For non-critical data, start a query without blocking navigation. Handle its rejection with `noop` so a background failure does not become an unhandled rejection: ```tsx -import { useQuery, useSuspenseQuery } from '@tanstack/react-query' +import { noop, useQuery, useSuspenseQuery } from '@tanstack/react-query' export const Route = createFileRoute('/dashboard')({ loader: ({ context }) => { // Await critical data - const user = context.queryClient.ensureQueryData(userQueryOptions) + const user = context.queryClient.query({ + ...userQueryOptions, + staleTime: 'static', + }) - // Start non-critical fetch without awaiting — streams during SSR - context.queryClient.prefetchQuery(analyticsQueryOptions) + // Start non-critical query without awaiting — streams during SSR + void context.queryClient.query({ ...analyticsQueryOptions }).catch(noop) return user }, @@ -304,7 +313,10 @@ import { useRouter } from '@tanstack/react-router' export const Route = createFileRoute('/posts')({ loader: ({ context }) => - context.queryClient.ensureQueryData(postsQueryOptions), + context.queryClient.query({ + ...postsQueryOptions, + staleTime: 'static', + }), errorComponent: PostsErrorComponent, component: PostsPage, }) @@ -373,24 +385,29 @@ export function createAppRouter() { } ``` -### 3. MEDIUM: Awaiting `prefetchQuery` in loader blocks rendering +### 3. MEDIUM: Awaiting a fire-and-forget query in a loader blocks rendering -`prefetchQuery` is designed to fire-and-forget. Awaiting it blocks the navigation transition until the data resolves, defeating the purpose of streaming. +A query used for streaming should start in the background and handle errors with `catch(noop)`. Awaiting it blocks the navigation transition until the data resolves, defeating the purpose of streaming. ```tsx +import { noop } from '@tanstack/react-query' + // WRONG — blocks navigation, no streaming benefit loader: async ({ context }) => { - await context.queryClient.prefetchQuery(analyticsQueryOptions) + await context.queryClient.query({ ...analyticsQueryOptions }).catch(noop) } -// CORRECT — fire and forget for streaming +// CORRECT — fire and forget for streaming, with handled rejection loader: ({ context }) => { - context.queryClient.prefetchQuery(analyticsQueryOptions) + void context.queryClient.query({ ...analyticsQueryOptions }).catch(noop) } -// If you need to block (critical data), use ensureQueryData instead: +// If you need to block (critical data), use a static query instead: loader: ({ context }) => { - return context.queryClient.ensureQueryData(criticalQueryOptions) + return context.queryClient.query({ + ...criticalQueryOptions, + staleTime: 'static', + }) } ``` @@ -415,8 +432,8 @@ const rootRoute = createRootRouteWithContext<{ queryClient: QueryClient }>()({ TanStack Router has its own SWR cache (`staleTime`, `gcTime`, `defaultPreloadStaleTime`). When using Query as an external cache: - Set `defaultPreloadStaleTime: 0` to prevent Router's cache from short-circuiting Query's freshness logic -- Router's `staleTime`/`gcTime` still apply to the loader return value. For pure Query patterns, return nothing from the loader (just `ensureQueryData` for the side effect) and read data exclusively from `useSuspenseQuery` -- `router.invalidate()` re-runs loaders (which call `ensureQueryData`), but Query decides whether to actually refetch based on its own `staleTime` +- Router's `staleTime`/`gcTime` still apply to the loader return value. For pure Query patterns, return nothing from the loader (just a static `query` for the side effect) and read data exclusively from `useSuspenseQuery` +- `router.invalidate()` re-runs loaders (which call `query` with `staleTime: 'static'`), so the cached Query data remains the freshness authority ## Cross-References diff --git a/packages/react-start/skills/react-start/server-components/SKILL.md b/packages/react-start/skills/react-start/server-components/SKILL.md index 1d0b0b099f..81561824a0 100644 --- a/packages/react-start/skills/react-start/server-components/SKILL.md +++ b/packages/react-start/skills/react-start/server-components/SKILL.md @@ -74,10 +74,10 @@ Treat TanStack Start RSCs as fetchable React Flight payloads, not as a framework - Simple server fragment in a route loader -> `renderServerComponent` - Interactive slot inside server markup -> `createCompositeComponent` -- Route component needs browser APIs but loader can still prefetch on the server -> `ssr: 'data-only'` +- Route component needs browser APIs but loader can still query on the server -> `ssr: 'data-only'` - Loader itself needs browser APIs -> `ssr: false` - Route cache key must include search params -> `loaderDeps` -- Query-managed RSC -> `useSuspenseQuery` + SSR `ensureQueryData` +- Query-managed RSC -> `useSuspenseQuery` + SSR `query` with `staleTime: 'static'` - Multiple independent RSCs -> separate server functions + `Promise.all` - Multiple RSCs sharing data or invalidating together -> one server function returning many renderables or sources - Need isolated widget failures or staggered reveal -> return promises from the loader and resolve with `use()` inside Suspense diff --git a/packages/react-start/skills/react-start/server-components/docs/caching-refresh-ssr.md b/packages/react-start/skills/react-start/server-components/docs/caching-refresh-ssr.md index 6619f78942..f48ba02d5b 100644 --- a/packages/react-start/skills/react-start/server-components/docs/caching-refresh-ssr.md +++ b/packages/react-start/skills/react-start/server-components/docs/caching-refresh-ssr.md @@ -73,10 +73,13 @@ const postQueryOptions = (postId: string) => ({ }) ``` -For SSR reuse, prefetch in the route loader: +For SSR reuse, run a static query in the route loader so cached data is reused without a stale refetch: ```tsx -await context.queryClient.ensureQueryData(postQueryOptions(params.postId)) +await context.queryClient.query({ + ...postQueryOptions(params.postId), + staleTime: 'static', +}) ``` Then read it with `useSuspenseQuery` in the component. diff --git a/packages/react-start/skills/react-start/server-components/examples/03-query-owned-rsc.tsx b/packages/react-start/skills/react-start/server-components/examples/03-query-owned-rsc.tsx index f22b481035..d891e2230d 100644 --- a/packages/react-start/skills/react-start/server-components/examples/03-query-owned-rsc.tsx +++ b/packages/react-start/skills/react-start/server-components/examples/03-query-owned-rsc.tsx @@ -1,5 +1,5 @@ // Query-owned RSC pattern. -// Assumes your router context provides a queryClient for SSR prefetch. +// Assumes your router context provides a queryClient for SSR queries. import type { ReactNode } from 'react' import { createFileRoute } from '@tanstack/react-router' @@ -68,7 +68,10 @@ const postQueryOptions = (postId: string) => ({ export const Route = createFileRoute('/posts/$postId')({ loader: async ({ context, params }) => { - await context.queryClient.ensureQueryData(postQueryOptions(params.postId)) + await context.queryClient.query({ + ...postQueryOptions(params.postId), + staleTime: 'static', + }) }, component: PostPage, }) diff --git a/packages/router-core/skills/router-core/type-safety/SKILL.md b/packages/router-core/skills/router-core/type-safety/SKILL.md index ce9204677e..15b9d35770 100644 --- a/packages/router-core/skills/router-core/type-safety/SKILL.md +++ b/packages/router-core/skills/router-core/type-safety/SKILL.md @@ -230,17 +230,17 @@ With file-based routing the route tree is generated, so this is handled for you. When using external caches like TanStack Query, don't let the router infer complex return types you never consume: ```tsx -// SLOWER — TS infers the full ensureQueryData return type into the route tree +// SLOWER — TS infers the full query return type into the route tree export const Route = createFileRoute('/posts/$postId')({ loader: ({ context: { queryClient }, params: { postId } }) => - queryClient.ensureQueryData(postQueryOptions(postId)), + queryClient.query({ ...postQueryOptions(postId), staleTime: 'static' }), component: PostComponent, }) -// FASTER — void return, inference stays out of the route tree +// FASTER — async loader returns no query data, inference stays out of the route tree export const Route = createFileRoute('/posts/$postId')({ - loader: async ({ context: { queryClient }, params: { postId } }) => { - await queryClient.ensureQueryData(postQueryOptions(postId)) + loader: async ({ context: { queryClient }, params: { postId: id } }) => { + await queryClient.query({ ...postQueryOptions(id), staleTime: 'static' }) }, component: PostComponent, })