Route-Based Code Splitting Example
An advanced usage example that shows how to implement route-based code splitting with TanStack Router, reducing initial load time by only loading the code necessary for the initial route.
import { lazy, Suspense } from 'react';
import { createBrowserRouter, RouterProvider } from '@tanstack/react-router';
// Lazy-load components for each route
const HomeComponent = lazy(() => import('./HomeComponent'));
const AboutComponent = lazy(() => import('./AboutComponent'));
// Define routes using createBrowserRouter
const router = createBrowserRouter([{
path: '/',
element: <Suspense fallback={<div>Loading...</div>}><HomeComponent /></Suspense>,
}, {
path: '/about',
element: <Suspense fallback={<div>Loading...</div>}><AboutComponent /></Suspense>,
}]);
function App() {
return <RouterProvider router={router} />;
}
export default App;
This code example demonstrates route-based code splitting with TanStack Router. It uses React's lazy for component lazy-loading and Suspense for handling the loading state. The createBrowserRouter function is used to define routes, each associated with a lazy-loaded component. During navigation, only the code necessary for rendering the active route is loaded, improving the application's initial load time.