router
🤖 Fully typesafe Router for React (and friends) w/ built-in caching, 1st class search-param APIs, client-side cache integration and isomorphic rendering.
Top Related Projects
Declarative routing for React
🥢 A minimalist-friendly ~2.1KB routing for React and Preact
🧭 Declarative, asynchronous routing for React.
Manage session history with JavaScript
Quick Overview
TanStack Router is a modern, lightweight, and type-safe routing library for React applications. It provides a powerful and flexible routing solution with built-in features like nested routing, automatic code-splitting, and TypeScript support.
Pros
- Type-safe routing with excellent TypeScript integration
- Automatic code-splitting for improved performance
- Nested routing support for complex application structures
- Seamless integration with React and other TanStack libraries
Cons
- Relatively new compared to more established routing libraries
- Steeper learning curve for developers used to traditional routing solutions
- Limited ecosystem and community resources compared to larger projects
- May require additional setup and configuration for some advanced use cases
Code Examples
- Defining routes:
import { createRouter } from '@tanstack/react-router'
const routeTree = createRouteTree({
home: {
path: '/',
component: HomeComponent,
},
users: {
path: '/users',
component: UsersComponent,
children: {
user: {
path: '$userId',
component: UserComponent,
},
},
},
})
const router = createRouter({ routeTree })
- Using Link component for navigation:
import { Link } from '@tanstack/react-router'
function Navigation() {
return (
<nav>
<Link to="/">Home</Link>
<Link to="/users">Users</Link>
<Link to="/users/$userId" params={{ userId: '123' }}>User 123</Link>
</nav>
)
}
- Accessing route parameters:
import { useParams } from '@tanstack/react-router'
function UserComponent() {
const { userId } = useParams()
return <div>User ID: {userId}</div>
}
Getting Started
- Install the library:
npm install @tanstack/react-router
- Create a router instance:
import { createRouter, createRouteTree } from '@tanstack/react-router'
const routeTree = createRouteTree({
// Define your routes here
})
const router = createRouter({ routeTree })
- Wrap your app with the RouterProvider:
import { RouterProvider } from '@tanstack/react-router'
function App() {
return (
<RouterProvider router={router}>
{/* Your app components */}
</RouterProvider>
)
}
Competitor Comparisons
Declarative routing for React
Pros of React Router
- Mature and widely adopted library with extensive community support
- Seamless integration with React applications
- Rich feature set including nested routing and route parameters
Cons of React Router
- Larger bundle size compared to TanStack Router
- More opinionated approach, which may limit flexibility in some cases
- Steeper learning curve for advanced features
Code Comparison
React Router:
import { BrowserRouter, Route, Switch } from 'react-router-dom';
<BrowserRouter>
<Switch>
<Route path="/home" component={Home} />
<Route path="/about" component={About} />
</Switch>
</BrowserRouter>
TanStack Router:
import { Router, Route, RootRoute } from '@tanstack/react-router';
const rootRoute = new RootRoute();
const homeRoute = new Route({ getParentRoute: () => rootRoute, path: '/home', component: Home });
const aboutRoute = new Route({ getParentRoute: () => rootRoute, path: '/about', component: About });
const routeTree = rootRoute.addChildren([homeRoute, aboutRoute]);
Both React Router and TanStack Router offer robust routing solutions for React applications. React Router benefits from its maturity and extensive ecosystem, while TanStack Router provides a more lightweight and flexible approach. The choice between the two depends on project requirements, team familiarity, and specific routing needs.
Pros of reach/router
- Simpler API with a more declarative approach to routing
- Built-in accessibility features, including focus management
- Smaller bundle size, which can lead to faster load times
Cons of reach/router
- Less active development and community support
- Limited flexibility for complex routing scenarios
- Fewer advanced features compared to TanStack Router
Code Comparison
reach/router:
import { Router } from "@reach/router"
<Router>
<Home path="/" />
<Dashboard path="dashboard" />
<Profile path="profile/:id" />
</Router>
TanStack Router:
import { RouterProvider, createRouter } from '@tanstack/react-router'
const routeTree = routeTreeFromChildren([
{ path: '/', element: <Home /> },
{ path: '/dashboard', element: <Dashboard /> },
{ path: '/profile/:id', element: <Profile /> },
])
const router = createRouter({ routeTree })
<RouterProvider router={router} />
Both routers offer declarative routing, but TanStack Router provides a more programmatic approach with its route tree creation. reach/router's syntax is more concise, while TanStack Router offers more flexibility and advanced features at the cost of slightly more verbose configuration.
🥢 A minimalist-friendly ~2.1KB routing for React and Preact
Pros of wouter
- Lightweight and minimalistic, with a smaller bundle size
- Simple API that's easy to learn and use
- No external dependencies, reducing potential conflicts
Cons of wouter
- Less feature-rich compared to router
- Limited support for advanced routing scenarios
- Smaller community and ecosystem
Code Comparison
wouter:
import { Route, Switch } from "wouter";
<Switch>
<Route path="/users/:id" component={UserProfile} />
<Route path="/about" component={About} />
</Switch>
router:
import { Route, Router, Routes } from "@tanstack/router";
<Router>
<Routes>
<Route path="/users/:id" element={<UserProfile />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
Summary
wouter is a lightweight and simple routing solution for React applications, ideal for smaller projects or those requiring minimal routing functionality. It offers a straightforward API and has no external dependencies, making it easy to integrate and maintain.
router, on the other hand, provides a more comprehensive routing solution with advanced features and a larger ecosystem. It's better suited for complex applications that require sophisticated routing capabilities and extensive customization options.
The choice between the two depends on the specific needs of your project, with wouter being a good fit for simpler applications and router being more appropriate for larger, more complex projects.
🧭 Declarative, asynchronous routing for React.
Pros of Navi
- Simpler API with less boilerplate code
- Built-in support for code-splitting and lazy loading
- Better integration with static site generation
Cons of Navi
- Less active development and community support
- Fewer advanced features compared to Router
- Limited documentation and examples
Code Comparison
Navi:
import { createBrowserNavigation } from 'navi';
const routes = {
'/': () => <HomePage />,
'/about': () => <AboutPage />,
};
const navigation = createBrowserNavigation({ routes });
Router:
import { Router, Route, Link } from '@tanstack/react-router';
const routeTree = rootRoute.addChildren([
new Route({
getParentRoute: () => rootRoute,
path: '/',
component: HomePage,
}),
new Route({
getParentRoute: () => rootRoute,
path: '/about',
component: AboutPage,
}),
]);
const router = new Router({ routeTree });
Navi offers a more concise syntax for defining routes, while Router provides a more object-oriented approach with additional configuration options. Navi's simplicity may be preferable for smaller projects, whereas Router's flexibility and feature set might be more suitable for larger, complex applications.
Manage session history with JavaScript
Pros of history
- Mature and widely adopted library with a long track record
- Simpler API focused solely on managing browser history
- Lightweight and easy to integrate into existing projects
Cons of history
- Limited to managing browser history and doesn't provide full routing capabilities
- Requires additional libraries or custom code for advanced routing features
- Less active development and fewer recent updates
Code Comparison
history:
import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
history.push('/new-path');
history.listen(({ location, action }) => {
console.log(action, location.pathname, location.state);
});
router:
import { Router, Route, Link } from '@tanstack/react-router';
const router = new Router({
routes: [
{ path: '/', element: <Home /> },
{ path: '/about', element: <About /> },
],
});
function App() {
return <RouterProvider router={router} />;
}
Summary
history is a focused library for managing browser history, while router is a more comprehensive routing solution. history is simpler and more lightweight, but router offers more advanced routing capabilities out of the box. The choice between them depends on the specific needs of your project and whether you require a full-featured routing system or just basic history management.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
ð¤ Type-safe router w/ built-in caching & URL state management for React!
Enjoy this library? Try the entire TanStack! React Query, React Table, React Charts, React Virtual
Visit tanstack.com/router for docs, guides, API and more!
Partners
Quick Features
- 100% TypeSafe
- Route Defs
- Navigation
- Relative Navigation
- Search Params
- Path Params
- Loaders
- 1st Class Search Params
- Schemas + Validation
- Parsing + Serialization
- Immutable
- Structural Sharing
- Pre/Post Processing
- Built-in Caching
- Stale-While-Revalidate
- Max-Age
- Auto Garbage Collection
- Invalidation
- Prefetching
- Automatic Prefetching
- Transitions
- Error Boundaries
- Code Splitting
- Layout Routes
- Easy Integration w/ external caches and storage (eg. React Query, Apollo, SWR, RTKQuery)
Example Usage
To run example React projects with Tanstack Router, see CONTRIBUTING.md
Top Related Projects
Declarative routing for React
🥢 A minimalist-friendly ~2.1KB routing for React and Preact
🧭 Declarative, asynchronous routing for React.
Manage session history with JavaScript
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot