Getting Started With Tanstack Router, Full type-safe routes for your react app

Getting Started With Tanstack Router, Full type-safe routes for your react app

·

2 min read

2022 was a fantastic year for web development, with the release of several new tools and frameworks that made it easier and more efficient to build modern web applications. One of the most exciting developments was the release of Tanstack Router, a fully typesafe router created by Tanner Linsley.

In this post, we will go through the process of setting up a React app using vite, a fast and lightweight alternative to traditional build tools like webpack, and integrating Tanstack Router to provide full type-safe routing for our application.

To get started, we will first need to install vite and create a new React app using the following commands:

npm create vite@latest

using this you will be able to set up a vite + react project, after setting up this we need to install the dependencies we will be using for this setup.

npm install @tanstack/react-router@beta --save

Now that we have all the necessary dependencies installed, we can start setting up our routes using Tanstack Router. First, let's import the RouteProvider component and create a new routes constant that will hold all of our routes config:

import {
  RouterProvider,
  createReactRouter,
  createRouteConfig,
  Link,
} from '@tanstack/react-router'

function App() {
  return (
    <RouteProvider router={routes} />
  )
}

Next, we will use the createRouteConfig to define our routes and pass in the routes constant as the value for the router prop:

const rootRouter = createRouteConfig({
// pass the component you want to render
    component: 
})

To add additional routes we can use the rootRouter with createRoute method on it, like this:

const homeRoute = rootRouter.createRoute({
    path: "home"
    component: Home
})

After that we need to make a 'createReactRouter' instance to pass into out routerProvide.

const routeConfig = rootRoute.addChildren([
  homeRoute,
]);

const router = createReactRouter({
  routeConfig,
  defaultPreload: 'intent',
});

the only thing remaining for our router to be fully type safe is to register it. this is how we do it.

// Register your router for typesafety
declare module '@tanstack/react-router' {
  interface RegisterRouter {
    router: typeof router;
  }
}

and you are done, your router is now fully typesafe everywhere in your app.

This was the basic setup of the new tanstack router, I will be continuing this series and showing other usecases and examples as well, make sure to like and follow for the same.