UNPKG

@tanstack/react-router

Version:

Modern and scalable routing for React applications

3 lines (2 loc) 39 kB
declare const _default: "# Overview\n\n**TanStack Router is a router for building React and Solid applications**. Some of its features include:\n\n- 100% inferred TypeScript support\n- Typesafe navigation\n- Nested Routing and layout routes (with pathless layouts)\n- Built-in Route Loaders w/ SWR Caching\n- Designed for client-side data caches (TanStack Query, SWR, etc.)\n- Automatic route prefetching\n- Asynchronous route elements and error boundaries\n- File-based Route Generation\n- Typesafe JSON-first Search Params state management APIs\n- Path and Search Parameter Schema Validation\n- Search Param Navigation APIs\n- Custom Search Param parser/serializer support\n- Search param middleware\n- Route matching/loading middleware\n\nTo get started quickly, head to the next page. For a more lengthy explanation, buckle up while I bring you up to speed!\n\n## \"A Fork in the Route\"\n\nUsing a router to build applications is widely regarded as a must-have and is usually one of the first choices you\u2019ll make in your tech stack.\n\n[//]: # 'WhyChooseTanStackRouter'\n\n**So, why should you choose TanStack Router over another router?**\n\nTo answer this question, we need to look at the other options in the space. There are many if you look hard enough, but in my experience, only a couple are worth exploring seriously:\n\n- **Next.js** - Widely regarded as the de facto framework for starting a new React project, it\u2019s laser focused on performance, workflow, and bleeding edge technology. Its APIs and abstractions are powerful, but can sometimes come across as non-standard. Its extremely fast growth and adoption in the industry has resulted in a featured packed experience, but not at the expense of feeling overwhelming and sometimes bloated.\n- **Remix / React Router** - A full-stack framework based on the historically successful React Router offers a similarly powerful developer and user experience, with APIs and vision based firmly on web standards like Request/Response and a focus on running anywhere JS can run. Many of its APIs and abstractions are wonderfully designed and were inspiration for more than a few TanStack Router APIs. That said, its rigid design, bolted-on type safety and sometimes strict over-adherence to platform APIs can leave some developers wanting more.\n\nBoth of these frameworks (and their routers) are great, and I can personally attest that both are very good solutions for building React applications. My experience has also taught me that these solutions could also be much better, especially around the actual routing APIs that are available to developers to make their apps faster, easier, and more enjoyable to work with.\n\nIt's probably no surprise at this point that picking a router is so important that it is often tied 1-to-1 with your choice of framework, since most frameworks rely on a specific router.\n\n[//]: # 'WhyChooseTanStackRouter'\n\n**Does this mean that TanStack Router is a framework?**\n\nTanStack Router itself is not a \"framework\" in the traditional sense, since it doesn't address a few other common full-stack concerns. However TanStack Router has been designed to be upgradable to a full-stack framework when used in conjunction with other tools that address bundling, deployments, and server-side-specific functionality. This is why we are currently developing [TanStack Start](https://tanstack.com/start), a full-stack framework that is built on top of TanStack Router and Vite.\n\nFor a deeper dive on the history of TanStack Router, feel free to read [TanStack Router's History](../decisions-on-dx.md#tanstack-routers-origin-story).\n\n## Why TanStack Router?\n\nTanStack Router delivers on the same fundamental expectations as other routers that you\u2019ve come to expect:\n\n- Nested routes, layout routes, grouped routes\n- File-based Routing\n- Parallel data loading\n- Prefetching\n- URL Path Params\n- Error Boundaries and Handling\n- SSR\n- Route Masking\n\nAnd it also delivers some new features that raise the bar:\n\n- 100% inferred TypeScript support\n- Typesafe navigation\n- Built-in SWR Caching for loaders\n- Designed for client-side data caches (TanStack Query, SWR, etc.)\n- Typesafe JSON-first Search Params state management APIs\n- Path and Search Parameter Schema Validation\n- Search Parameter Navigation APIs\n- Custom Search Param parser/serializer support\n- Search param middleware\n- Inherited Route Context\n- Mixed file-based and code-based routing\n\nLet\u2019s dive into some of the more important ones in more detail!\n\n## 100% Inferred TypeScript Support\n\nEverything these days is written \u201Cin Typescript\u201D or at the very least offers type definitions that are veneered over runtime functionality, but too few packages in the ecosystem actually design their APIs with TypeScript in mind. So while I\u2019m pleased that your router is auto-completing your option fields and catching a few property/method typos here and there, there is much more to be had.\n\n- TanStack Router is fully aware of all of your routes and their configuration at any given point in your code. This includes the path, path params, search params, context, and any other configuration you\u2019ve provided. Ultimately this means that you can navigate to any route in your app with 100% type safety and confidence that your link or navigate call will succeed.\n- TanStack Router provides lossless type-inference. It uses countless generic type parameters to enforce and propagate any type information you give it throughout the rest of its API and ultimately your app. No other router offers this level of type safety and developer confidence.\n\nWhat does all of that mean for you?\n\n- Faster feature development with auto-completion and type hints\n- Safer and faster refactors\n- Confidence that your code will work as expected\n\n## 1st Class Search Parameters\n\nSearch parameters are often an afterthought, treated like a black box of strings (or string) that you can parse and update, but not much else. Existing solutions are **not** type-safe either, adding to the caution that is required to deal with them. Even the most \"modern\" frameworks and routers and leave it up to you to figure out how to manage this state. Sometimes they'll parse the search string into an object for you, or sometimes you're left to do it yourself with `URLSearchParams`.\n\nLet's step back and remember that **search params are the most powerful state manager in your entire application.** They are global, serializable, bookmarkable, and shareable making them the perfect place to store any kind of state that needs to survive a page refresh or a social share.\n\nTo live up to that responsibility, search parameters are a first-class citizen in TanStack Router. While still based on standard URLSearchParams, TanStack Router uses a powerful parser/serializer to manage deeper and more complex data structures in your search params, all while keeping them type-safe and easy to work with.\n\n**It's like having `useState` right in the URL!**\n\nSearch parameters are:\n\n- Automatically parsed and serialized as JSON\n- Validated and typed\n- Inherited from parent routes\n- Accessible in loaders, components, and hooks\n- Easily modified with the useSearch hook, Link, navigate, and router.navigate APIs\n- Customizable with a custom search filters and middleware\n- Subscribed via fine-grained search param selectors for efficient re-renders\n\nOnce you start using TanStack Router's search parameters, you'll wonder how you ever lived without them.\n\n## Built-In Caching and Friendly Data Loading\n\nData loading is a critical part of any application and while most existing routers offer some form of critical data loading APIs, they often fall short when it comes to caching and data lifecycle management. Existing solutions suffer from a few common problems:\n\n- No caching at all. Data is always fresh, but your users are left waiting for frequently accessed data to load over and over again.\n- Overly-aggressive caching. Data is cached for too long, leading to stale data and a poor user experience.\n- Blunt invalidation strategies and APIs. Data may be invalidated too often, leading to unnecessary network requests and wasted resources, or you may not have any fine-grained control over when data is invalidated at all.\n\nTanStack Router solves these problems with a two-prong approach to caching and data loading:\n\n### Built-in Cache\n\nTanStack Router provides a light-weight built-in caching layer that works seamlessly with the Router. This caching layer is loosely based on TanStack Query, but with fewer features and a much smaller API surface area. Like TanStack Query, sane but powerful defaults guarantee that your data is cached for reuse, invalidated when necessary, and garbage collected when not in use. It also provides a simple API for invalidating the cache manually when needed.\n\n### Flexible & Powerful Data Lifecycle APIs\n\nTanStack Router is designed with a flexible and powerful data loading API that more easily integrates with existing data fetching libraries like TanStack Query, SWR, Apollo, Relay, or even your own custom data fetching solution. Configurable APIs like `context`, `beforeLoad`, `loaderDeps` and `loader` work in unison to make it easy to define declarative data dependencies, prefetch data, and manage the lifecycle of an external data source with ease.\n\n## Inherited Route Context\n\nTanStack Router's router and route context is a powerful feature that allows you to define context that is specific to a route which is then inherited by all child routes. Even the router and root routes themselves can provide context. Context can be built up both synchronously and asynchronously, and can be used to share data, configuration, or even functions between routes and route configurations. This is especially useful for scenarios like:\n\n- Authentication and Authorization\n- Hybrid SSR/CSR data fetching and preloading\n- Theming\n- Singletons and global utilities\n- Curried or partial application across preloading, loading, and rendering stages\n\nAlso, what would route context be if it weren't type-safe? TanStack Router's route context is fully type-safe and inferred at zero cost to you.\n\n## File-based and/or Code-Based Routing\n\nTanStack Router supports both file-based and code-based routing at the same time. This flexibility allows you to choose the approach that best fits your project's needs.\n\nTanStack Router's file-based routing approach is uniquely user-facing. Route configuration is generated for you either by the Vite plugin or TanStack Router CLI, leaving the usage of said generated code up to you! This means that you're always in total control of your routes and router, even if you use file-based routing.\n\n## Acknowledgements\n\nTanStack Router builds on concepts and patterns popularized by many other OSS projects, including:\n\n- [TRPC](https://trpc.io/)\n- [Remix](https://remix.run)\n- [Chicane](https://swan-io.github.io/chicane/)\n- [Next.js](https://nextjs.org)\n\nWe acknowledge the investment, risk and research that went into their development, but are excited to push the bar they have set even higher.\n\n## Let's go!\n\nEnough overview, there's so much more to do with TanStack Router. Hit that next button and let's get started!\n\n# Quick Start\n\nIf you're feeling impatient and prefer to skip all of our wonderful documentation, here is the bare minimum to get going with TanStack Router using both file-based route generation and code-based route configuration:\n\n## Using File-Based Route Generation\n\nFile based route generation (through Vite, and other supported bundlers) is the recommended way to use TanStack Router as it provides the best experience, performance, and ergonomics for the least amount of effort.\n\n### Scaffolding Your First TanStack Router Project\n\n```sh\nnpx create-tsrouter-app@latest my-app --template file-router\n```\n\nSee [create-tsrouter-app](https://github.com/TanStack/create-tsrouter-app/tree/main/cli/create-tsrouter-app) for more options.\n\n### Manual Setup\n\nAlternatively, you can manually setup the project using the following steps:\n\n#### Install TanStack Router, Vite Plugin, and the Router Devtools\n\n```sh\nnpm install @tanstack/react-router @tanstack/react-router-devtools\nnpm install -D @tanstack/router-plugin\n# or\npnpm add @tanstack/react-router @tanstack/react-router-devtools\npnpm add -D @tanstack/router-plugin\n# or\nyarn add @tanstack/react-router @tanstack/react-router-devtools\nyarn add -D @tanstack/router-plugin\n# or\nbun add @tanstack/react-router @tanstack/react-router-devtools\nbun add -D @tanstack/router-plugin\n# or\ndeno add npm:@tanstack/react-router npm:@tanstack/router-plugin npm:@tanstack/react-router-devtools\n```\n\n#### Configure the Vite Plugin\n\n```tsx\n// vite.config.ts\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport { tanstackRouter } from '@tanstack/router-plugin/vite'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [\n // Please make sure that '@tanstack/router-plugin' is passed before '@vitejs/plugin-react'\n tanstackRouter({\n target: 'react',\n autoCodeSplitting: true,\n }),\n react(),\n // ...,\n ],\n})\n```\n\n> [!TIP]\n> If you are not using Vite, or any of the supported bundlers, you can check out the [TanStack Router CLI](../routing/installation-with-router-cli.md) guide for more info.\n\nCreate the following files:\n\n- `src/routes/__root.tsx` (with two '`_`' characters)\n- `src/routes/index.tsx`\n- `src/routes/about.tsx`\n- `src/main.tsx`\n\n#### `src/routes/__root.tsx`\n\n```tsx\nimport { createRootRoute, Link, Outlet } from '@tanstack/react-router'\nimport { TanStackRouterDevtools } from '@tanstack/react-router-devtools'\n\nexport const Route = createRootRoute({\n component: () => (\n <>\n <div className=\"p-2 flex gap-2\">\n <Link to=\"/\" className=\"[&.active]:font-bold\">\n Home\n </Link>{' '}\n <Link to=\"/about\" className=\"[&.active]:font-bold\">\n About\n </Link>\n </div>\n <hr />\n <Outlet />\n <TanStackRouterDevtools />\n </>\n ),\n})\n```\n\n#### `src/routes/index.tsx`\n\n```tsx\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/')({\n component: Index,\n})\n\nfunction Index() {\n return (\n <div className=\"p-2\">\n <h3>Welcome Home!</h3>\n </div>\n )\n}\n```\n\n#### `src/routes/about.tsx`\n\n```tsx\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/about')({\n component: About,\n})\n\nfunction About() {\n return <div className=\"p-2\">Hello from About!</div>\n}\n```\n\n#### `src/main.tsx`\n\nRegardless of whether you are using the `@tanstack/router-plugin` package and running the `npm run dev`/`npm run build` scripts, or manually running the `tsr watch`/`tsr generate` commands from your package scripts, the route tree file will be generated at `src/routeTree.gen.ts`.\n\nImport the generated route tree and create a new router instance:\n\n```tsx\nimport { StrictMode } from 'react'\nimport ReactDOM from 'react-dom/client'\nimport { RouterProvider, createRouter } from '@tanstack/react-router'\n\n// Import the generated route tree\nimport { routeTree } from './routeTree.gen'\n\n// Create a new router instance\nconst router = createRouter({ routeTree })\n\n// Register the router instance for type safety\ndeclare module '@tanstack/react-router' {\n interface Register {\n router: typeof router\n }\n}\n\n// Render the app\nconst rootElement = document.getElementById('root')!\nif (!rootElement.innerHTML) {\n const root = ReactDOM.createRoot(rootElement)\n root.render(\n <StrictMode>\n <RouterProvider router={router} />\n </StrictMode>,\n )\n}\n```\n\nIf you are working with this pattern you should change the `id` of the root `<div>` on your `index.html` file to `<div id='root'></div>`\n\n## Using Code-Based Route Configuration\n\n> [!IMPORTANT]\n> The following example shows how to configure routes using code, and for simplicity's sake is in a single file for this demo. While code-based generation allows you to declare many routes and even the router instance in a single file, we recommend splitting your routes into separate files for better organization and performance as your application grows.\n\n```tsx\nimport { StrictMode } from 'react'\nimport ReactDOM from 'react-dom/client'\nimport {\n Outlet,\n RouterProvider,\n Link,\n createRouter,\n createRoute,\n createRootRoute,\n} from '@tanstack/react-router'\nimport { TanStackRouterDevtools } from '@tanstack/react-router-devtools'\n\nconst rootRoute = createRootRoute({\n component: () => (\n <>\n <div className=\"p-2 flex gap-2\">\n <Link to=\"/\" className=\"[&.active]:font-bold\">\n Home\n </Link>{' '}\n <Link to=\"/about\" className=\"[&.active]:font-bold\">\n About\n </Link>\n </div>\n <hr />\n <Outlet />\n <TanStackRouterDevtools />\n </>\n ),\n})\n\nconst indexRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: '/',\n component: function Index() {\n return (\n <div className=\"p-2\">\n <h3>Welcome Home!</h3>\n </div>\n )\n },\n})\n\nconst aboutRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: '/about',\n component: function About() {\n return <div className=\"p-2\">Hello from About!</div>\n },\n})\n\nconst routeTree = rootRoute.addChildren([indexRoute, aboutRoute])\n\nconst router = createRouter({ routeTree })\n\ndeclare module '@tanstack/react-router' {\n interface Register {\n router: typeof router\n }\n}\n\nconst rootElement = document.getElementById('app')!\nif (!rootElement.innerHTML) {\n const root = ReactDOM.createRoot(rootElement)\n root.render(\n <StrictMode>\n <RouterProvider router={router} />\n </StrictMode>,\n )\n}\n```\n\nIf you glossed over these examples or didn't understand something, we don't blame you, because there's so much more to learn to really take advantage of TanStack Router! Let's move on.\n\n# Devtools\n\n> Link, take this sword... I mean Devtools!... to help you on your way!\n\nWave your hands in the air and shout hooray because TanStack Router comes with dedicated devtools! \uD83E\uDD73\n\nWhen you begin your TanStack Router journey, you'll want these devtools by your side. They help visualize all of the inner workings of TanStack Router and will likely save you hours of debugging if you find yourself in a pinch!\n\n## Installation\n\nThe devtools are a separate package that you need to install:\n\n```sh\nnpm install @tanstack/react-router-devtools\n```\n\nor\n\n```sh\npnpm add @tanstack/react-router-devtools\n```\n\nor\n\n```sh\nyarn add @tanstack/react-router-devtools\n```\n\nor\n\n```sh\nbun add @tanstack/react-router-devtools\n```\n\n## Import the Devtools\n\n```js\nimport { TanStackRouterDevtools } from '@tanstack/react-router-devtools'\n```\n\n## Using Devtools in production\n\nThe Devtools, if imported as `TanStackRouterDevtools` will not be shown in production. If you want to have devtools in an environment with `process.env.NODE_ENV === 'production'`, use instead `TanStackRouterDevtoolsInProd`, which has all the same options:\n\n```tsx\nimport { TanStackRouterDevtoolsInProd } from '@tanstack/react-router-devtools'\n```\n\n## Using inside of the `RouterProvider`\n\nThe easiest way for the devtools to work is to render them inside of your root route (or any other route). This will automatically connect the devtools to the router instance.\n\n```tsx\nconst rootRoute = createRootRoute({\n component: () => (\n <>\n <Outlet />\n <TanStackRouterDevtools />\n </>\n ),\n})\n\nconst routeTree = rootRoute.addChildren([\n // ... other routes\n])\n\nconst router = createRouter({\n routeTree,\n})\n\nfunction App() {\n return <RouterProvider router={router} />\n}\n```\n\n## Manually passing the Router Instance\n\nIf rendering the devtools inside of the `RouterProvider` isn't your cup of tea, a `router` prop for the devtools accepts the same `router` instance you pass to the `Router` component. This makes it possible to place the devtools anywhere on the page, not just inside the provider:\n\n```tsx\nfunction App() {\n return (\n <>\n <RouterProvider router={router} />\n <TanStackRouterDevtools router={router} />\n </>\n )\n}\n```\n\n## Floating Mode\n\nFloating Mode will mount the devtools as a fixed, floating element in your app and provide a toggle in the corner of the screen to show and hide the devtools. This toggle state will be stored and remembered in localStorage across reloads.\n\nPlace the following code as high in your React app as you can. The closer it is to the root of the page, the better it will work!\n\n```js\nimport { TanStackRouterDevtools } from '@tanstack/react-router-devtools'\n\nfunction App() {\n return (\n <>\n <Router />\n <TanStackRouterDevtools initialIsOpen={false} />\n </>\n )\n}\n```\n\n### Devtools Options\n\n- `router: Router`\n - The router instance to connect to.\n- `initialIsOpen: Boolean`\n - Set this `true` if you want the devtools to default to being open.\n- `panelProps: PropsObject`\n - Use this to add props to the panel. For example, you can add `className`, `style` (merge and override default style), etc.\n- `closeButtonProps: PropsObject`\n - Use this to add props to the close button. For example, you can add `className`, `style` (merge and override default style), `onClick` (extend default handler), etc.\n- `toggleButtonProps: PropsObject`\n - Use this to add props to the toggle button. For example, you can add `className`, `style` (merge and override default style), `onClick` (extend default handler), etc.\n- `position?: \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\"`\n - Defaults to `bottom-left`.\n - The position of the TanStack Router logo to open and close the devtools panel.\n- `shadowDOMTarget?: ShadowRoot`\n - Specifies a Shadow DOM target for the devtools.\n - By default, devtool styles are applied to the `<head>` tag of the main document (light DOM). When a `shadowDOMTarget` is provided, styles will be applied within this Shadow DOM instead.\n- `containerElement?: string | any`\n - Use this to render the devtools inside a different type of container element for ally purposes.\n - Any string which corresponds to a valid intrinsic JSX element is allowed.\n - Defaults to 'footer'.\n\n## Fixed Mode\n\nTo control the position of the devtools, import the `TanStackRouterDevtoolsPanel`:\n\n```js\nimport { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'\n```\n\nIt can then be attached to provided shadow DOM target:\n\n```js\n<TanStackRouterDevtoolsPanel\n shadowDOMTarget={shadowContainer}\n router={router}\n/>\n```\n\nClick [here](https://tanstack.com/router/latest/docs/framework/react/examples/basic-devtools-panel) to see a live example of this in StackBlitz.\n\n## Embedded Mode\n\nEmbedded Mode will embed the devtools as a regular component in your application. You can style it however you'd like after that!\n\n```js\nimport { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'\n\nfunction App() {\n return (\n <>\n <Router router={router} />\n <TanStackRouterDevtoolsPanel\n router={router}\n style={styles}\n className={className}\n />\n </>\n )\n}\n```\n\n### DevtoolsPanel Options\n\n- `router: Router`\n - The router instance to connect to.\n- `style: StyleObject`\n - The standard React style object used to style a component with inline styles.\n- `className: string`\n - The standard React className property used to style a component with classes.\n- `isOpen?: boolean`\n - A boolean variable indicating whether the panel is open or closed.\n- `setIsOpen?: (isOpen: boolean) => void`\n - A function that toggles the open and close state of the panel.\n- `handleDragStart?: (e: any) => void`\n - Handles the opening and closing the devtools panel.\n- `shadowDOMTarget?: ShadowRoot`\n - Specifies a Shadow DOM target for the devtools.\n - By default, devtool styles are applied to the `<head>` tag of the main document (light DOM). When a `shadowDOMTarget` is provided, styles will be applied within this Shadow DOM instead.\n\n# Migration from React Router Checklist\n\n**_If your UI is blank, open the console, and you will probably have some errors that read something along the lines of `cannot use 'useNavigate' outside of context` . This means there are React Router api\u2019s that are still imported and referenced that you need to find and remove. The easiest way to make sure you find all React Router imports is to uninstall `react-router-dom` and then you should get typescript errors in your files. Then you will know what to change to a `@tanstack/react-router` import._**\n\nHere is the [example repo](https://github.com/Benanna2019/SickFitsForEveryone/tree/migrate-to-tanstack/router/React-Router)\n\n- [ ] Install Router - `npm i @tanstack/react-router`\n- [ ] **Optional:** Uninstall React Router to get TypeScript errors on imports.\n - At this point I don\u2019t know if you can do a gradual migration, but it seems likely you could have multiple router providers, not desirable.\n - The api\u2019s between React Router and TanStack Router are very similar and could most likely be handled in a sprint cycle or two if that is your companies way of doing things.\n- [ ] Create Routes for each existing React Router route we have\n- [ ] Create root route\n- [ ] Create router instance\n- [ ] Add global module in main.tsx\n- [ ] Remove any React Router (`createBrowserRouter` or `BrowserRouter`), `Routes`, and `Route` Components from main.tsx\n- [ ] **Optional:** Refactor `render` function for custom setup/providers - The repo referenced above has an example - This was necessary in the case of Supertokens. Supertoken has a specific setup with React Router and a different setup with all other React implementations\n- [ ] Set RouterProvider and pass it the router as the prop\n- [ ] Replace all instances of React Router `Link` component with `@tanstack/react-router` `Link` component\n - [ ] Add `to` prop with literal path\n - [ ] Add `params` prop, where necessary with params like so `params={{ orderId: order.id }}`\n- [ ] Replace all instances of React Router `useNavigate` hook with `@tanstack/react-router` `useNavigate` hook\n - [ ] Set `to` property and `params` property where needed\n- [ ] Replace any React Router `Outlet`'s with the `@tanstack/react-router` equivalent\n- [ ] If you are using `useSearchParams` hook from React Router, move the search params default value to the validateSearch property on a Route definition.\n - [ ] Instead of using the `useSearchParams` hook, use `@tanstack/react-router` `Link`'s search property to update the search params state\n - [ ] To read search params you can do something like the following\n - `const { page } = useSearch({ from: productPage.fullPath })`\n- [ ] If using React Router\u2019s `useParams` hook, update the import to be from `@tanstack/react-router` and set the `from` property to the literal path name where you want to read the params object from\n - So say we have a route with the path name `orders/$orderid`.\n - In the `useParams` hook we would set up our hook like so: `const params = useParams({ from: \"/orders/$orderId\" })`\n - Then wherever we wanted to access the order id we would get it off of the params object `params.orderId`\n\n# Migration from React Location\n\nBefore you begin your journey in migrating from React Location, it's important that you have a good understanding of the [Routing Concepts](../routing/routing-concepts.md) and [Design Decisions](../decisions-on-dx.md) used by TanStack Router.\n\n## Differences between React Location and TanStack Router\n\nReact Location and TanStack Router share much of same design decisions concepts, but there are some key differences that you should be aware of.\n\n- React Location uses _generics_ to infer types for routes, while TanStack Router uses _module declaration merging_ to infer types.\n- Route configuration in React Location is done using a single array of route definitions, while in TanStack Router, route configuration is done using a tree of route definitions starting with the [root route](../routing/routing-concepts.md#the-root-route).\n- [File-based routing](../routing/file-based-routing.md) is the recommended way to define routes in TanStack Router, while React Location only allows you to define routes in a single file using a code-based approach.\n - TanStack Router does support a [code-based approach](../routing/code-based-routing.md) to defining routes, but it is not recommended for most use cases. You can read more about why, over here: [why is file-based routing the preferred way to define routes?](../decisions-on-dx.md#3-why-is-file-based-routing-the-preferred-way-to-define-routes)\n\n## Migration guide\n\nIn this guide we'll go over the process of migrating the [React Location Basic example](https://github.com/TanStack/router/tree/react-location/examples/basic) over to TanStack Router using file-based routing, with the end goal of having the same functionality as the original example (styling and other non-routing related code will be omitted).\n\n> [!TIP]\n> To use a code-based approach for defining your routes, you can read the [code-based Routing](../routing/code-based-routing.md) guide.\n\n### Step 1: Swap over to TanStack Router's dependencies\n\nFirst, we need to install the dependencies for TanStack Router.\n\n```sh\nnpm install @tanstack/react-router @tanstack/router-devtools\n```\n\nAnd remove the React Location dependencies.\n\n```sh\nnpm uninstall @tanstack/react-location @tanstack/react-location-devtools\n```\n\n### Step 2: Use the file-based routing watcher\n\nIf your project uses Vite (or one of the supported bundlers), you can use the TanStack Router plugin to watch for changes in your routes files and automatically update the routes configuration.\n\nInstallation of the Vite plugin:\n\n```sh\nnpm install -D @tanstack/router-plugin\n```\n\nAnd add it to your `vite.config.js`:\n\n```js\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport { tanstackRouter } from '@tanstack/router-plugin/vite'\n\nexport default defineConfig({\n // ...\n plugins: [tanstackRouter(), react()],\n})\n```\n\nHowever, if your application does not use Vite, you use one of our other [supported bundlers](../routing/file-based-routing.md#getting-started-with-file-based-routing), or you can use the `@tanstack/router-cli` package to watch for changes in your routes files and automatically update the routes configuration.\n\n### Step 3: Add the file-based configuration file to your project\n\nCreate a `tsr.config.json` file in the root of your project with the following content:\n\n```json\n{\n \"routesDirectory\": \"./src/routes\",\n \"generatedRouteTree\": \"./src/routeTree.gen.ts\"\n}\n```\n\nYou can find the full list of options for the `tsr.config.json` file [here](../routing/file-based-routing.md#options).\n\n### Step 4: Create the routes directory\n\nCreate a `routes` directory in the `src` directory of your project.\n\n```sh\nmkdir src/routes\n```\n\n### Step 5: Create the root route file\n\n```tsx\n// src/routes/__root.tsx\nimport { createRootRoute, Outlet, Link } from '@tanstack/react-router'\nimport { TanStackRouterDevtools } from '@tanstack/router-devtools'\n\nexport const Route = createRootRoute({\n component: () => {\n return (\n <>\n <div>\n <Link to=\"/\" activeOptions={{ exact: true }}>\n Home\n </Link>\n <Link to=\"/posts\">Posts</Link>\n </div>\n <hr />\n <Outlet />\n <TanStackRouterDevtools />\n </>\n )\n },\n})\n```\n\n### Step 6: Create the index route file\n\n```tsx\n// src/routes/index.tsx\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/')({\n component: Index,\n})\n```\n\n> You will need to move any related components and logic needed for the index route from the `src/index.tsx` file to the `src/routes/index.tsx` file.\n\n### Step 7: Create the posts route file\n\n```tsx\n// src/routes/posts.tsx\nimport { createFileRoute, Link, Outlet } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/posts')({\n component: Posts,\n loader: async () => {\n const posts = await fetchPosts()\n return {\n posts,\n }\n },\n})\n\nfunction Posts() {\n const { posts } = Route.useLoaderData()\n return (\n <div>\n <nav>\n {posts.map((post) => (\n <Link\n key={post.id}\n to={`/posts/$postId`}\n params={{ postId: post.id }}\n >\n {post.title}\n </Link>\n ))}\n </nav>\n <Outlet />\n </div>\n )\n}\n```\n\n> You will need to move any related components and logic needed for the posts route from the `src/index.tsx` file to the `src/routes/posts.tsx` file.\n\n### Step 8: Create the posts index route file\n\n```tsx\n// src/routes/posts.index.tsx\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/posts/')({\n component: PostsIndex,\n})\n```\n\n> You will need to move any related components and logic needed for the posts index route from the `src/index.tsx` file to the `src/routes/posts.index.tsx` file.\n\n### Step 9: Create the posts id route file\n\n```tsx\n// src/routes/posts.$postId.tsx\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/posts/$postId')({\n component: PostsId,\n loader: async ({ params: { postId } }) => {\n const post = await fetchPost(postId)\n return {\n post,\n }\n },\n})\n\nfunction PostsId() {\n const { post } = Route.useLoaderData()\n // ...\n}\n```\n\n> You will need to move any related components and logic needed for the posts id route from the `src/index.tsx` file to the `src/routes/posts.$postId.tsx` file.\n\n### Step 10: Generate the route tree\n\nIf you are using one of the supported bundlers, the route tree will be generated automatically when you run the dev script.\n\nIf you are not using one of the supported bundlers, you can generate the route tree by running the following command:\n\n```sh\nnpx tsr generate\n```\n\n### Step 11: Update the main entry file to render the Router\n\nOnce you've generated the route-tree, you can then update the `src/index.tsx` file to create the router instance and render it.\n\n```tsx\n// src/index.tsx\nimport React from 'react'\nimport ReactDOM from 'react-dom'\nimport { createRouter, RouterProvider } from '@tanstack/react-router'\n\n// Import the generated route tree\nimport { routeTree } from './routeTree.gen'\n\n// Create a new router instance\nconst router = createRouter({ routeTree })\n\n// Register the router instance for type safety\ndeclare module '@tanstack/react-router' {\n interface Register {\n router: typeof router\n }\n}\n\nconst domElementId = 'root' // Assuming you have a root element with the id 'root'\n\n// Render the app\nconst rootElement = document.getElementById(domElementId)\nif (!rootElement) {\n throw new Error(`Element with id ${domElementId} not found`)\n}\n\nReactDOM.createRoot(rootElement).render(\n <React.StrictMode>\n <RouterProvider router={router} />\n </React.StrictMode>,\n)\n```\n\n### Finished!\n\nYou should now have successfully migrated your application from React Location to TanStack Router using file-based routing.\n\nReact Location also has a few more features that you might be using in your application. Here are some guides to help you migrate those features:\n\n- [Search params](../guide/search-params.md)\n- [Data loading](../guide/data-loading.md)\n- [History types](../guide/history-types.md)\n- [Wildcard / Splat / Catch-all routes](../routing/routing-concepts.md#splat--catch-all-routes)\n- [Authenticated routes](../guide/authenticated-routes.md)\n\nTanStack Router also has a few more features that you might want to explore:\n\n- [Router Context](../guide/router-context.md)\n- [Preloading](../guide/preloading.md)\n- [Pathless Layout Routes](../routing/routing-concepts.md#pathless-layout-routes)\n- [Route masking](../guide/route-masking.md)\n- [SSR](../guide/ssr.md)\n- ... and more!\n\nIf you are facing any issues or have any questions, feel free to ask for help in the TanStack Discord.\n\n# Frequently Asked Questions\n\nWelcome to the TanStack Router FAQ! Here you'll find answers to common questions about the TanStack Router. If you have a question that isn't answered here, please feel free to ask in the [TanStack Discord](https://tlinz.com/discord).\n\n## Should I commit my `routeTree.gen.ts` file into git?\n\nYes! Although the route tree file (i.e. `routeTree.gen.ts`) is generated by the TanStack Router, it is essentially towards the runtime of your application. It is not a build artifact. The route tree file is a critical part of your application's source code, and it is used by the TanStack Router to build your application's routes at runtime.\n\nYou should commit this file into git so that other developers can use it to build your application.\n\n## Can I conditionally render the Root Route component?\n\nNo, the root route is always rendered as it is the entry point of your application.\n\nIf you need to conditionally render a route's component, this usually means that the page content needs to be different based on some condition (e.g. user authentication). For this use case, you should use a [Layout Route](../routing/routing-concepts.md#layout-routes) or a [Pathless Layout Route](../routing/routing-concepts.md#pathless-layout-routes) to conditionally render the content.\n\nYou can restrict access to these routes using a conditional check in the `beforeLoad` function of the route.\n\n<details>\n<summary>What does this look like?</summary>\n\n```tsx\n// src/routes/_pathless-layout.tsx\nimport { createFileRoute, Outlet } from '@tanstack/react-router'\nimport { isAuthenticated } from '../utils/auth'\n\nexport const Route = createFileRoute('/_pathless-layout', {\n beforeLoad: async () => {\n // Check if the user is authenticated\n const authed = await isAuthenticated()\n if (!authed) {\n // Redirect the user to the login page\n return '/login'\n }\n },\n component: PathlessLayoutRouteComponent,\n // ...\n})\n\nfunction PathlessLayoutRouteComponent() {\n return (\n <div>\n <h1>You are authed</h1>\n <Outlet />\n </div>\n )\n}\n```\n\n</details>\n\n"; export default _default;