React Router v7 🚦
React Router v7 leans into “framework mode”: it handles routing, data loading, mutations, and SSR in one cohesive package inspired by Remix.
1) Data Loaders & Actions 🧾
- Loaders fetch data before rendering a route; they run on navigation and can stream responses.
- Actions handle mutations triggered via forms or imperative submissions.
const router = createBrowserRouter([
{
path: "/projects",
element: <Projects />,
loader: async ({ request }) => {
const res = await fetch("/api/projects", { signal: request.signal });
return res.json();
},
action: async ({ request }) => {
const formData = await request.formData();
await fetch("/api/projects", { method: "POST", body: formData });
return null;
}
}
]);- Hooks like
useLoaderData,useActionData, anduseNavigationexpose data + pending state in components.
2) Type Generation Workflows 🧠
- Use
@react-router/devCLI to generate TypeScript types from route modules, ensuringuseLoaderData<typeof loader>()infers precise shapes. - Integrate with
tsconfig.jsonpaths so route files share enums/interfaces.
Workflow:
- Define loaders/actions with typed return values.
- Run
npx @react-router/dev typegen. - Import generated helper types for strong typing across nested routes.
3) SSR Framework Mode 🌐
- React Router v7 includes
createStaticHandlerandcreateStaticRouterfor server-side rendering. - Render on the server with loaders resolving data, stream HTML, and hydrate with the same route tree client-side.
- Works with Node, Bun, or even edge runtimes when fetch APIs are available.
const { query, dataRoutes } = createStaticHandler(routes);
const context = await query(request);
const router = createStaticRouter(dataRoutes, context);
const stream = renderToPipeableStream(<RouterProvider router={router} />);- Framework mode handles errors with route-specific
ErrorBoundaryexports and supports deferred data viadefer().
Key Takeaways ✅
- React Router v7 elevates loaders/actions to first-class concepts, mirroring Remix.
- Type generation keeps data access strongly typed even across nested routes.
- SSR APIs let you build custom frameworks (or extend Remix) with streamed HTML + hydration.
Recap 🔄
React Router v7’s framework mode is a middle ground between vanilla routing and full frameworks: define loaders/actions, generate types, and render on the server with streaming-friendly primitives to get a cohesive data + routing solution.
Last updated on