tanstack-router-data-loaders
Skill10 starsChanged 6 months agoMITView on GitHub
Use when adding TanStack Router loaders, pending/error components, search-param schemas, or integrating loaders with TanStack Query. Not for plain React Router apps without TanStack Router.
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-prefetch-and-hydrationSkill
- tanstack-query-alternativeSkill
- tanstack-start-server-routesSkill
- typed-api-hooks-formsSkill
The file
We split this skill into the rules it gives an agent
6 rules. About 0 are common, 4 are distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈4
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 53
Use this in both the loader and the component so they share one cache key.
- Distinctive: line 100
Search params become typed, validated, and shareable URLs — back-button works for free.
- Distinctive: line 127
All three start in parallel.
- Very specific: line 131
Use route beforeLoad to short-circuit unauthenticated users:
- Distinctive: line 147
If the app uses TanStack Start or any SSR, loaders run on the server first.
- Very specific: line 151
Don't invalidate inside a loader — loaders are for reads.
≈ “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 Router data loaders
TanStack Router provides typed routes with loaders that run before a route renders. Pair them with TanStack Query so data is prefetched, cached, and reused — no "flash of loading skeleton" on intra-app navigation.
Companion skills: tanstack-query-alternative, tanstack-prefetch-and-hydration, tanstack-start-server-routes, error-states-and-empty-ui.
File-based route with a loader
// app/routes/projects.$id.tsx
import { createFileRoute } from "@tanstack/react-router";
import { projectQueryOptions } from "~/api/projects";
export const Route = createFileRoute("/projects/$id")({
loader: ({ context: { queryClient }, params }) =>
queryClient.ensureQueryData(projectQueryOptions(params.id)),
pendingComponent: ProjectSkeleton,
errorComponent: ({ error, reset }) => <ProjectError error={error} reset={reset} />,
component: ProjectPage,
});
function ProjectPage() {
const { id } = Route.useParams();
const { data: project } = useSuspenseQuery(projectQueryOptions(id));
return <ProjectDetail project={project} />;
}ensureQueryData is the loader-friendly version of prefetchQuery: returns the cached value or fetches once. The useSuspenseQuery in the component then reads from cache synchronously — no loading state needed.
queryOptions factory (single source of truth)
// src/api/projects.ts
import { queryOptions } from "@tanstack/react-query";
export const projectQueryOptions = (id: string) =>
queryOptions({
queryKey: ["projects", "detail", id],
queryFn: () => fetchProject(id),
staleTime: 30_000,
});Use this in both the loader and the component so they share one cache key. Centralize per-resource options here.
Provide the QueryClient via router context
// app/router.tsx
import { createRouter } from "@tanstack/react-router";
import { queryClient } from "~/lib/query-client";
import { routeTree } from "./routeTree.gen";
export const router = createRouter({
routeTree,
context: { queryClient },
defaultPreload: "intent", // prefetch on hover/focus
defaultPendingMinMs: 300, // avoid skeleton flash for fast loads
});defaultPreload: "intent" makes every <Link> hover prefetch — pairs well with tanstack-prefetch-and-hydration.
Search-param schemas (typed querystrings)
import { z } from "zod";
const searchSchema = z.object({
status: z.enum(["active", "archived"]).default("active"),
page: z.number().int().min(1).default(1),
});
export const Route = createFileRoute("/projects")({
validateSearch: searchSchema,
loaderDeps: ({ search }) => ({ status: search.status, page: search.page }),
loader: ({ context: { queryClient }, deps }) =>
queryClient.ensureQueryData(projectListQueryOptions(deps)),
component: ProjectList,
});In the component:
const { status, page } = Route.useSearch();
const navigate = Route.useNavigate();
<Button onClick={() => navigate({ search: (p) => ({ ...p, page: p.page + 1 }) })}>Next</Button>Search params become typed, validated, and shareable URLs — back-button works for free.
Pending and error components
pendingComponent: render only when the loader takes longer thandefaultPendingMinMs. Use skeletons matching the page layout.errorComponent: receiveserrorandreset— callreset()from a retry button.- For 404s on detail pages, throw
notFound()inside the loader and define a route-levelnotFoundComponent.
loader: async ({ context, params }) => {
const project = await context.queryClient.ensureQueryData(projectQueryOptions(params.id));
if (!project) throw notFound();
return project;
},Parallel loaders for sibling data
loader: ({ context: { queryClient }, params }) =>
Promise.all([
queryClient.ensureQueryData(projectQueryOptions(params.id)),
queryClient.ensureQueryData(membersQueryOptions(params.id)),
queryClient.ensureQueryData(activityQueryOptions(params.id)),
]),All three start in parallel; the route renders when all resolve.
Auth-gated routes
Use route beforeLoad to short-circuit unauthenticated users:
export const Route = createFileRoute("/app")({
beforeLoad: ({ context, location }) => {
if (!context.auth.user) {
throw redirect({ to: "/login", search: { redirect: location.href } });
}
},
});Provide auth in the router context alongside queryClient.
SSR / hydration
If the app uses TanStack Start or any SSR, loaders run on the server first. Dehydrate the QueryClient and hydrate on the client so loaders don't refetch — see tanstack-prefetch-and-hydration.
Mutations and invalidation from loaders
Don't invalidate inside a loader — loaders are for reads. Invalidate in mutation onSuccess (tanstack-mutations-and-invalidation); the next navigation's ensureQueryData picks up the fresh value.
Avoid
- Two
queryKeys for the same resource (loader vs component) — always use thequeryOptionsfactory. - Fetching inside
useEffecton the page when a loader already loaded the data. - Long synchronous work in a loader (it blocks navigation).
- Skipping
pendingComponentfor slow loaders — users see a blank screen. - Overusing
useSuspenseQueryoutside of routes that already ran the loader (you'll suspend the whole tree).
Checklist
- Every detail route has a loader +
queryOptionsfactory. defaultPreload: "intent"enabled in the router.- Search params validated with a Zod schema.
- Pending and error components defined per route (or sensible global defaults).
- Auth routes use
beforeLoad+redirect.
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.

