Route Loaders for Data Fetching
You'll learn how to implement fully type-safe loader functions in TanStack Router that fetch data before your components render, with automatic type inference flowing into your components.
What Are Route Loaders?
Route loaders in TanStack Router are functions that run before a route renders, similar to React Router's loader concept but with complete TypeScript integration. The key difference? Your component automatically knows the exact shape of the data returned—no manual typing needed.
Think of loaders as a pre-flight checklist: the route won't render until the loader completes, ensuring your component always has the data it needs from the first render. No loading states, no useEffect races.
Defining a Typed Loader
You define loaders directly in your route configuration:
const userRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/users/$userId',
loader: async ({ params }) => {
const response = await fetch(`/api/users/${params.userId}`);
return { user: await response.json() };
}
});
The params object is fully typed based on your path definition ($userId becomes params.userId). The loader's return type is automatically inferred.
Consuming Loader Data
Inside your component, use useLoaderData():
function UserProfile() {
const { user } = useLoaderData({ from: userRoute.id });
// `user` is automatically typed—no manual typing needed!
return <h1>{user.name}</h1>;
}
TypeScript knows what your loader returns. Change the loader's structure, and your component immediately shows type errors. This end-to-end safety eliminates an entire class of bugs.
Key Takeaway: TanStack Router's typed loaders fetch data before rendering with complete type inference, giving you compile-time guarantees that your components receive exactly the data they expect—no manual type annotations required.