tanstack-prefetch-and-hydration
Skill10 starsChanged 6 months agoMITView on GitHub
Use when prefetching TanStack Query data on hover/route-enter, hydrating server-rendered queries, or speeding up navigation. Not for CSR-only apps where prefetch isn't desired or for non-TanStack stacks.
In this repository56 other files it gives its agents.
- accessibility-passSkill
- analytics-eventsSkill
- api-error-handlingSkill
- audit-logging-backendSkill
- background-jobs-and-cronSkill
- dark-mode-and-themingSkill
- dashboard-charts-rechartsSkill
- edge-functions-and-webhooksSkill
- email-and-notificationsSkill
- error-states-and-empty-uiSkill
- feature-flags-and-togglesSkill
- file-upload-storageSkill
- i18n-multi-languageSkill
- lovable-prompting-playbookSkill
- lovable-ship-checklistSkill
- migration-playbookSkill
- multi-tenant-backendSkill
- onboarding-copySkill
- optimistic-updatesSkill
- payment-failed-and-recoverySkill
- payment-webhook-idempotencySkill
- payment-webhook-testingSkill
- performance-budgetSkill
- pg-cron-recipesSkill
- pg-cron-scheduled-jobsSkill
- pg-cron-with-pg-net-edgeSkill
- postgres-full-text-searchSkill
- postgres-triggers-and-functionsSkill
- pricing-and-billingSkill
- programmatic-seo-content-qualitySkill
- programmatic-seo-pagesSkill
- rate-limiting-edgeSkill
- realtime-and-subscriptionsSkill
- refactor-safe-diffSkill
- release-notesSkill
- seo-core-web-vitalsSkill
- seo-landing-pageSkill
- seo-meta-tags-spaSkill
- seo-sitemap-generationSkill
- seo-ssr-and-prerenderingSkill
- seo-structured-dataSkill
- server-input-validationSkill
- shadcn-patternsSkill
- soft-delete-and-archivingSkill
- stripe-one-time-payment-webhooksSkill
- stripe-payment-webhooksSkill
- supabase-auth-flowsSkill
- supabase-database-designSkill
- supabase-rls-and-authSkill
- support-replySkill
- tanstack-infinite-queriesSkill
- tanstack-mutations-and-invalidationSkill
- tanstack-query-alternativeSkill
- tanstack-router-data-loadersSkill
- tanstack-start-server-routesSkill
- typed-api-hooks-formsSkill
The file
We split this skill into the rules it gives an agent
1 rule. About 0 are common, 1 is distinctive, and 0 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 70
When the page is server-rendered or prerendered, ship a serialized cache so the client doesn't refetch immediately.
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
TanStack prefetch and hydration
Make routes feel instant. Prefetch on intent (hover, focus, route prepare); hydrate when SSR or prerendering is used.
Companion skills: tanstack-query-alternative, seo-ssr-and-prerendering, performance-budget.
Prefetch on hover / focus
function ProjectLink({ project }: { project: Project }) {
const qc = useQueryClient();
return (
<Link
to={`/projects/${project.id}`}
onMouseEnter={() =>
qc.prefetchQuery({
queryKey: projectKeys.detail(project.id),
queryFn: () => fetchProject(project.id),
staleTime: 30_000,
})
}
onFocus={() =>
qc.prefetchQuery({
queryKey: projectKeys.detail(project.id),
queryFn: () => fetchProject(project.id),
})
}
>
{project.name}
</Link>
);
}staleTime on the prefetch matches the consumer — otherwise the consumer refetches immediately after navigation.
Prefetch on route enter (React Router)
// router config
{
path: "projects/:id",
loader: async ({ params }) => {
await queryClient.prefetchQuery({
queryKey: projectKeys.detail(params.id!),
queryFn: () => fetchProject(params.id!),
});
return null;
},
element: <ProjectPage />,
}In the page, useQuery reads from cache without a flash:
const { data } = useQuery({ queryKey: projectKeys.detail(id), queryFn: () => fetchProject(id) });Hydration (SSR / prerender)
When the page is server-rendered or prerendered, ship a serialized cache so the client doesn't refetch immediately.
Server (or build-time)
import { dehydrate, QueryClient } from "@tanstack/react-query";
const qc = new QueryClient();
await qc.prefetchQuery({ queryKey: pageKeys.detail(slug), queryFn: () => fetchPage(slug) });
const dehydratedState = dehydrate(qc);
// embed into HTML
res.send(`
<html>
<body>
<div id="root">${html}</div>
<script>window.__RQ_STATE__ = ${JSON.stringify(dehydratedState).replace(/</g, "\\u003c")};</script>
</body>
</html>
`);Client
import { HydrationBoundary } from "@tanstack/react-query";
<QueryClientProvider client={queryClient}>
<HydrationBoundary state={window.__RQ_STATE__}>
<App />
</HydrationBoundary>
</QueryClientProvider>Hydrated entries are treated as fresh until staleTime elapses.
When to prefetch (and when not)
| Prefetch | Don't prefetch |
| Card → detail page links above the fold | Pages users rarely visit (settings deep links) |
| Wizard "next step" data | Expensive queries that may go unused |
| Predictable nav (breadcrumbs) | Authenticated data on public marketing pages |
Each prefetch is a real network request — over-prefetching wastes bandwidth and Supabase egress.
Background revalidation strategy
staleTime: 0→ refetch on every mount (fresh, costly).staleTime: 30_000→ trust cache for 30 s, then refetch in background.staleTime: Infinitywith explicit invalidation → ideal for static config (feature flags, plans list) you mutate via specific actions.
Avoid
- Prefetching everything on app start.
staleTime: 0everywhere — defeats caching.- Sending the dehydrated state without
JSON.stringifyescape; it's an XSS vector. - Prefetching authenticated queries on hover in a logged-out shell.
Checklist
- Hover/focus prefetch on primary navigation links.
- Route loader prefetches detail data before render where applicable.
- If SSR/prerender used,
HydrationBoundarywraps the app. staleTimetuned per resource, not global zero.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

