Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 39 ยท Loaders and Data Loading

Typed Loader Data and Route Types

See how React Router v7 generates types for params, loader data and component props, how serialization affects types, and how to type shared loader helpers yourself.

In older Remix versions you wrote useLoaderData<typeof loader>() and relied on a helper to convert types after serialization. React Router v7 framework mode replaces that with type generation: a build step writes a +types module next to each route, and your loader and component get correct types from it automatically.

The generator itself cannot run on this site, so TypeScript here is read-only. The stand-ins are plain JavaScript that show the runtime facts behind the types, mainly what survives serialization.

Generated route types

Run the dev server or react-router typegen and a .react-router/types folder appears with a +types/<route>.ts file per route. You import Route from it:

TSX
// app/routes/products.$id.tsx
import type { Route } from "./+types/products.$id";

export async function loader({ params }: Route.LoaderArgs) {
  // params.id is typed as string, because the path has :id
  const product = await getProduct(params.id);
  if (!product) throw new Response("Not found", { status: 404 });
  return { product, fetchedAt: new Date() };
}

export default function ProductPage({ loaderData, params }: Route.ComponentProps) {
  // loaderData.product and loaderData.fetchedAt (a Date) are typed from the loader
  return <h1>{loaderData.product.name}</h1>;
}

The generated types know your route's params from the path pattern (so a typo like params.idd is a compile error), and your loader data from whatever the loader returns. Add a tsconfig.json entry so the generated folder is included:

JSON
{
  "include": [".react-router/types/**/*", "app/**/*"],
  "compilerOptions": { "rootDirs": [".", "./.react-router/types"] }
}

The rootDirs setting makes ./+types/... resolve to the generated file even though it lives in a different folder.

Other generated argument types

Type Used for
Route.LoaderArgs the argument of loader
Route.ActionArgs the argument of action
Route.ComponentProps props of the default export: loaderData, actionData, params, matches
Route.MetaArgs the argument of meta
Route.ErrorBoundaryProps props of ErrorBoundary
Route.ClientLoaderArgs the argument of clientLoader

Serialization changes what the browser sees

Loader data crosses the network, so the client receives a serialized copy. React Router's format keeps Date, Map, Set, BigInt, undefined and promises intact, and the generated types reflect that. It still cannot send class instances with methods or functions: those lose their behaviour or fail.

JS Stand-in: what JSON loses compared to a richer format

Press Run (or Ctrl + Enter) to see the console output here.

No output.

structuredClone here is a rough model of why a rich serializer is useful. It is not what the router uses, but it shows the idea: dates stay dates.

Class instances: convert before returning

If your database layer returns objects with methods or getters, convert them to plain data first.

TSX
class Money {
  constructor(public cents: number) {}
  format() { return `$${(this.cents / 100).toFixed(2)}`; }
}

export async function loader() {
  const price = new Money(1999);
  return { price: price.format() };      // good: a string
  // return { price };                    // risky: the method is lost on the client
}
JS Stand-in: methods are lost when data is copied as plain data

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Typing shared helpers

A function you call from several loaders needs explicit types, since there is no route to generate them from:

TSX
import type { Route } from "./+types/products";

type Pagination = { page: number; pages: number };

export function readPagination(request: Request, total: number, pageSize = 10): Pagination {
  const page = Math.max(1, Number(new URL(request.url).searchParams.get("page")) || 1);
  return { page, pages: Math.max(1, Math.ceil(total / pageSize)) };
}

For data from another route, use useRouteLoaderData("routes/root") and narrow with a type guard, because it may be undefined when that route is not matched. Alternatively export a named type from the route module and import it with import type.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where do the Route types come from in React Router v7?

    The dev server or react-router typegen writes types next to each route.
  2. 2. Which type describes the props of a route's default export?

    ComponentProps includes loaderData, actionData, params and matches.
  3. 3. What happens to a class instance's methods when it is returned from a loader?

    Only data crosses the network, not behaviour.
  4. 4. Why is rootDirs set in tsconfig?

    The generated files live in .react-router/types but are imported as siblings.

Summary

  • Typegen creates Route types for params, loader data and props; import them from ./+types/<file>.
  • The serializer keeps Dates, Maps, Sets and promises, but not methods or functions.
  • Return plain data; convert rich objects before returning.
  • Shared helpers need explicit types.

Next: Client Loaders and Hydration