agentleFS
charanjit-singhcharanjit-singh/lovable-skills/skills/tanstack-router-data-loaders/SKILL.md

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.

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
  1. Distinctive:

    Use this in both the loader and the component so they share one cache key.

    line 53
  2. Distinctive:

    Search params become typed, validated, and shareable URLs — back-button works for free.

    line 100
  3. Distinctive:

    All three start in parallel.

    line 127
  4. Very specific:

    Use route beforeLoad to short-circuit unauthenticated users:

    line 131
  5. Distinctive:

    If the app uses TanStack Start or any SSR, loaders run on the server first.

    line 147
  6. Very specific:

    Don't invalidate inside a loader — loaders are for reads.

    line 151

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

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 than defaultPendingMinMs. Use skeletons matching the page layout.
  • errorComponent: receives error and reset — call reset() from a retry button.
  • For 404s on detail pages, throw notFound() inside the loader and define a route-level notFoundComponent.
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 the queryOptions factory.
  • Fetching inside useEffect on the page when a loader already loaded the data.
  • Long synchronous work in a loader (it blocks navigation).
  • Skipping pendingComponent for slow loaders — users see a blank screen.
  • Overusing useSuspenseQuery outside of routes that already ran the loader (you'll suspend the whole tree).

Checklist

  • Every detail route has a loader + queryOptions factory.
  • 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.

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.