data-loading
FreeNo executable scriptsNot checkedRoute loader option, loaderDeps for cache keys, staleTime/gcTime/ defaultPreloadStaleTime SWR caching, pendingComponent/pendingMs/ pendingMinMs…
by TanStack★ 15,408 GitHub starsAbout this skill
Data Loading
Setup
Basic loader returning data, consumed via useLoaderData:
// src/routes/posts.tsx
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/posts')({
loader: () => fetchPosts(),
component: PostsComponent,
})
function PostsComponent() {
const posts = Route.useLoaderData()
return (
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
)
}
In code-split components, use getRouteApi instead of importing Route:
import { getRouteApi } from '@tanstack/react-router'
const routeApi = getRouteApi('/posts')
function PostsComponent() {
const posts = routeApi.useLoaderData()
return <ul>{/* ... */}</ul>
}
Route Loading Lifecycle
The router executes this sequence on every URL/history update:
- Route Matching (top-down)
route.params.parseroute.validateSearch
- Route Pre-Loading (serial)
route.beforeLoadroute.onError→route.errorComponent
- Route Loading (parallel)
route.component.preload?route.loaderroute.pendingComponent(optional)route.component
route.onError→route.errorComponent
Key: beforeLoad runs before loader. beforeLoad for a parent runs before its children's beforeLoad. Throwing in beforeLoad prevents all children from loading.
Core Patterns
loaderDeps for Search-Param-Driven Cache Keys
Loaders don't receive search params directly. Use loaderDeps to declare which search params affect the cache key:
// src/routes/posts.tsx
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/posts')({
validateSearch: (search) => ({
offset: Number(search.offset) || 0,
limit: Number(search.limit) || 10,
}),
loaderDeps: ({ search: { offset, limit } }) => ({ offset, limit }),
loader: ({ deps: { offset, limit } }) => fetchPosts({ offset, limit }),
})
When deps change, the route reloads regardless of staleTime.
SWR Caching Configuration
TanStack Router has built-in Stale-While-Revalidate caching keyed on the route's parsed pathname + loaderDeps.
Defaults:
staleTime: 0 — data is always considered stale, reloads in background on re-matchpreloadStaleTime: 30 seconds — preloaded data won't be refetched for 30sgcTime: 30 minutes — unused cache entries garbage collected after 30min
export const Route = createFileRoute('/posts')({
loader: () => fetchPosts(),
staleTime: 10_000, // 10s: data considered fresh for 10 seconds
gcTime: 5 * 60 * 1000, // 5min: garbage collect after 5 minutes
})
Disable SWR caching entirely:
export const Route = createFileRoute('/posts')({
loader: () => fetchPosts(),
staleTime: Infinity,
})
Globally:
const router = createRouter({
routeTree,
defaultStaleTime: Infinity,
})
Pending States (pendingComponent / pendingMs / pendingMinMs)
By default, a pending component shows after 1 second (pendingMs: 1000) and stays for at least 500ms (pendingMinMs: 500) to avoid flash.
export const Route = createFileRoute('/posts')({
loader: () => fetchPosts(),
pendingMs: 500,
pendingMinMs: 300,
pendingComponent: () => <div>Loading posts...</div>,
component: PostsComponent,
})
Router Context with createRootRouteWithContext (Factory Pattern)
createRootRouteWithContext is a factory that returns a function. You must call it twice — the first call passes the generic type, the second passes route options:
// src/routes/__root.tsx
import { createRootRouteWithContext, Outlet } from '@tanstack/react-router'
interface MyRouterContext {
auth: { userId: string }
fetchPosts: () => Promise<Post[]>
}
// NOTE: double call — createRootRouteWithContext<Type>()({...})
export const Route = createRootRouteWithContext<MyRouterContext>()({
component: () => <Outlet />,
})
Supply the context when creating the router:
// src/router.tsx
import { createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'
const router = createRouter({
routeTree,
context: {
auth: { userId: '123' },
fetchPosts,
},
})
Consume in loaders and beforeLoad:
// src/routes/posts.tsx
export const Route = createFileRoute('/posts')({
loader: ({ context: { fetchPosts } }) => fetchPosts(),
})
To pass React hook values into the router context, call the hook above RouterProvider and inject via the context prop:
import { RouterProvider } from '@tanstack/react-router'
function InnerApp() {
const auth = useAuth()
return <RouterProvider router={router} context={{ auth }} />
}
function App() {
return (
<AuthProvider>
<InnerApp />
</AuthProvider>
)
}
Route-level context via beforeLoad:
export const Route = createFileRoute('/posts')({
beforeLoad: ({ context }) => ({
fetchPosts: context.f
Install data-loading in Claude Code & Claude Desktop
Sign up to install this skill
Create a free account to reveal the install command and save the skill to your library.
- Reveal the one-line install command
- Save skills to your synced library
- Get notified when skills update
Allowed tools
Tools this skill is permitted to call.
No restriction — this skill can use any tool.
FAQ
What does the data-loading skill do?
Route loader option, loaderDeps for cache keys, staleTime/gcTime/ defaultPreloadStaleTime SWR caching, pendingComponent/pendingMs/ pendingMinMs, errorComponent/onError/onCatch, beforeLoad, router context and createRootRouteWithContext DI pattern, router.invalidate, Await component, deferred data loading with unawaited promises.
How do I install the data-loading skill?
Copy the skill folder into ~/.claude/skills (the Claude Code tab above does this in one command), or install it as a plugin.
Does the data-loading skill run scripts?
No, this skill is instructions only (SKILL.md) with no executable scripts.
Related skills
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
by Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
by Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
by Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
by Anthropic