Hubert
10 min
May 23, 2025

TanStack Router - Getting started with a modern router for React

Routing is the foundation of any modern SPA (Single Page Application). It is responsible for how users navigate between views without reloading the entire page. TanStack Router is a modern routing library built for React that prioritizes full TypeScript support, transparency and advanced data and parameter management capabilities. Thanks to its integration with the TanStack ecosystem (e.g. TanStack Query), this router allows you to build scalable and efficient applications. In this article, we will look at its capabilities and how to get started with this tool from scratch.

Read more
TanStack Router - Getting started with a modern router for React
Schedule a free consultation

    We process your data in accordance with our privacy policy.

    What is the TanStack Router?

    TanStack Router is a state-of-the-art library for managing routing in React-based applications, created by the developers of popular TanStack family tools such as TanStack Query (formerly React Query). The project was created in response to the growing need for better integration of routing with data management, full typing and flexibility in defining routes. Unlike classic solutions such as React Router, TanStack Router was designed from the beginning with full TypeScript compatibility in mind. Every element – from paths to URL parameters to query strings – is covered by strict type control, which significantly increases code security and developer comfort.

    With support for both file-based and code-based routing, TanStack Router works well for a variety of project scales. It has built-in data loading mechanisms and advanced query parameter management to create efficient and well-structured applications. The whole is complemented by a modern architecture that integrates routing, typing and data logic into a coherent application development platform.

    Key features of TanStack Router

    TanStack Router stands out from other routing libraries thanks to its modern architecture and deep integration with the TypeScript ecosystem. Its design allows not only intuitive route definition, but also full control over data and application parameters. Below are the most important features that make it one of the most interesting solutions for React developers.

    Full compatibility with TypeScript (end-to-end type safety)
    One of the most important advantages of TanStack Router is its strong typing – this includes not only the paths and parameters themselves, but also data passed to components, query strings and data returned from loaders. This makes it possible to detect many errors already at the compilation stage, which translates into greater code stability and convenience.

    The flexible routing system
    TanStack Router offers two approaches to defining routes:

    • File-based routing – inspired by solutions known from Next.js, allows you to create a route structure based on the layout of files in the routes/ folder.
    • Code-based routing – allows you to dynamically define routes using code, which gives you full control over the navigation logic.

    Built-in data loaders
    Router has native support for loaders that allow you to download data even before the component is rendered. It works with TanStack Query, among others, and supports the stale-while-revalidate (SWR) approach, making the application faster and more responsive.

    Advanced handling of query parameters (query params)
    TanStack Router offers a powerful system for working with query strings:

    • parameter selection and validation,
    • serialization of complex objects (e.g., JSON),
    • inheritance of parameter schemas in nested routes,
    • parameter transformations using middleware.

    Optimizing Rendering Performance
    By using structured data sharing and router state selectors, applications built on TanStack Router minimize the number of unnecessary renders. Components listen only for specific pieces of state that apply to them.

    Extensive developer tools (devtools)
    Official debugging tools allow you to view router status, current paths, errors, loader data or query parameters – all in a clear interface.

    Need support with your IT projects? We have the experience!
    Need support with your IT projects? We have the experience!
    Need support with your IT projects? We have the experience!
    Write to us!

    Installation and configuration of TanStack Router

    Getting started with TanStack Router is relatively easy, although it requires knowledge of TypeScript and basic React application structure. The router can be deployed in both new projects and existing applications, replacing a legacy routing system (such as React Router).

    How to get started with TanStack Router? Installation

    To add TanStack Router to your React project, simply install the appropriate package:

    npm install @tanstack/react-router
    

    If you’re using TypeScript (and it’s definitely worth it to get the most out of this library), make sure you have a properly configured tsconfig.json file .

    Creating routes

    TanStack Router supports both file-based routing (file-based) and software-defined routing (code-based). In this example, we will focus on the file-based approach – preferred for larger projects.

    The structure of the routes folder may look as follows:

    src/
    ┗ routes/
       ┣ __root.tsx     // main layout 
       ┣ index.tsx      // path "/"
       ┗ about.tsx      // path "/about"
    

    Each file in the routes folder represents one route. An example of the contents of about.tsx:

    import { createFileRoute } from '@tanstack/react-router'
    
    export const Route = createFileRoute('/about')({
      component: () => <h1>About us</h1>,
    })
    

    Creating a router

    After defining the routes, you create an instance of the router. If you are using file-based routing, you will generate the file routeTree.gen.ts:

    import { createRouter } from '@tanstack/react-router'
    import { routeTree } from './routeTree.gen'
    
    export const router = createRouter({ routeTree })
    

    Connecting the router to the application

    To make the router work, you need to surround the application with the RouterProvider component :

    import { RouterProvider } from '@tanstack/react-router'
    import { router } from './router'
    
    function App() {
      return <RouterProvider router={router} />
    }
    

    This step ensures that all navigation and routing context is available inside your application.

    Launching the application

    After these steps, you can launch the application and navigate between pages like any other SPA application. TanStack Router automatically handles data reloading, parameter changes and rendering of relevant components.

    With its modular structure and full type control, TanStack Router allows you to build applications in a structured and predictable way from the start. In the following sections, we’ll look at its advantages and limitations, which you should know before implementing it in a larger project.

    Example of operation – first application

    To better understand how TanStack Router works in practice, it is useful to build a simple application with several routes, parameter handling and data loading. Let’s assume that we create an application with three views: a home page, an “About Us” sub-page and a dynamic user details page.

    Folder structure

    src/
    ┣ routes/
    ┃ ┣ __root.tsx
    ┃ ┣ index.tsx         // "/"
    ┃ ┣ about.tsx         // "/about"
    ┃ ┗ user.$userId.tsx  // "/user/:userId"
    ┣ router.ts
    ┣ App.tsx
    ┗ main.tsx
    

    File __root.tsx – main layout

    import { Outlet } from '@tanstack/react-router'
    
    export const Route = {
      component: () => (
        <div>
          <nav>
            <a href="/">Start</a> | <a href="/about">About us</a>
          </nav>
          <hr />
          <Outlet />
        </div>
      ),
    }
    

    Homepage – index.tsx

    import { createFileRoute } from '@tanstack/react-router'
    
    export const Route = createFileRoute('/')({
      component: () => <h2>Welcome to the homepage</h2>,
    })
    

    Page “About us” – about.tsx

    import { createFileRoute } from '@tanstack/react-router'
    
    export const Route = createFileRoute('/about')({
      component: () => <p>This is subpage about our company.</p>,
    })
    

    Dynamic user route – user.$userId.tsx

    import { createFileRoute } from '@tanstack/react-router'
    
    export const Route = createFileRoute('/user/$userId')({
      loader: async ({ params }) => {
        const res = await fetch(`https://jsonplaceholder.typicode.com/users/${params.userId}`)
        return await res.json()
      },
      component: ({ useLoader }) => {
        const user = useLoader()
        return (
          <div>
            <h3>{user.name}</h3>
            <p>{user.email}</p>
          </div>
        )
      },
    })
    

    Router.ts file – router configuration

    import { createRouter } from '@tanstack/react-router'
    import { routeTree } from './routeTree.gen'
    
    export const router = createRouter({ routeTree })
    

    Application – App.tsx

    import { RouterProvider } from '@tanstack/react-router'
    import { router } from './router'
    
    export default function App() {
      return <RouterProvider router={router} />
    }
    

    Run the application as usual(npm run dev in the case of Vite), then:

    • visit / – you will see the home page,
    • go to /about – the content of the “About us” subpage,
    • enter, for example, /user/1– user data will be dynamically retrieved from the API.

    Advantages of TanStack Routera

    TanStack Router is a tool that combines a number of modern solutions, improving the quality and security of work on React applications. Thanks to its careful architecture and integration with TypeScript and TanStack Query, it is able to provide functionalities that are hard to find in other routers.

    One of its biggest advantages is full compatibility with TypeScript. This means that all aspects of routing – paths, parameters, query strings, loader data – are strictly typed. Errors that in other libraries would only appear at runtime in the application, here are detected already at the compilation stage. This significantly increases the stability of the code and gives the programmer a greater sense of control.

    The modularity and flexibility of routing is also a great advantage – applications can be built both in a file structure-based style and through dynamic, code-based route definition. This makes it easy to tailor TanStack Router to individual project needs.

    Also worth noting:

    • Integrated data loading – the ability to download data from the server before rendering components, with caching, retry, and revalidation options.
    • Advanced query parameter handling – with type validation, inheritance, and middleware.
    • High rendering performance – thanks to state selectors and structural data splitting.
    • Support for SSR and React Server Components – making this router ready for development towards modern architectures.
    • A set of developer tools (Devtools) – allowing you to track routes, errors, and data without leaving your browser.

    All this makes TanStack Router not only fast and secure, but also ready for large, demanding projects where stability, typing and performance are key.

    Disadvantages of TanStack Routera

    Although TanStack Router offers many modern and advanced features, it is not a solution without drawbacks. Before deciding to implement it in a project, it is worth understanding the potential limitations and difficulties that may arise during the implementation and development stages of the application.

    First of all, TanStack Router is a relatively new library, which means that there are fewer educational materials, tutorials, and ready-made examples available compared to established solutions such as React Router. For novice developers, this can mean a more difficult start and the need to delve deeper into the technical documentation.

    The high entry threshold resulting from strong typing and integration with TypeScript can also be a major barrier. While this is a huge advantage in terms of stability and code quality, it requires the team to have a good knowledge of TypeScript and be willing to work with generic types and more complex type structures.

    Other potential drawbacks include:

    • lack of support for older versions of React – TanStack Router assumes a modern API and may not be compatible with legacy applications.
    • required integration with a build system (e.g., generating routeTree.gen.ts), which in some cases can complicate the CI/CD process.
    • smaller community and ecosystem – which means slower development of some features or less frequent updates to extensions.

    It is also worth noting that some features – such as middleware for query params or schema inheritance control – while very powerful, can lead to excessive abstraction if used incorrectly in smaller projects.

    Summary

    TanStack Router is a modern, ambitious alternative to classic routing libraries in React. It combines strong typing, modularity, and deep integration with data management systems – all with the goal of increasing predictability, stability, and code quality. Thanks to its TypeScript-based approach, developers gain a tool that not only helps build scalable applications but also avoids many classes of errors before the project even launches.

    However, this solution is not for everyone. The team must be prepared for a higher entry threshold and the need for a deeper understanding of types and application architecture. Where fast implementation and low entry costs are important, classic React Router may be sufficient. But where scalability, performance, and type safety are priorities, TanStack Router is clearly ahead of the competition.

    It’s worth testing it out for yourself, even in a smaller project, to see if its philosophy and style of work fit the way you build applications. For many developers, this may be a step towards a more modern, robust frontend.

    Connected articles
    See all
    Discover more topics