Blog>
Snippets

Optimizing Navigation with Route-based Code Splitting

Explains how to implement route-based code splitting in TanStack Router, using dynamic import() statements to lazily load components.
import { createBrowserRouter, RouterProvider } from 'tanstack-router';
import React, { lazy, Suspense } from 'react';
Imports necessary components and functions from 'tanstack-router' and 'react'. 'lazy' is used for dynamic imports.
const Home = lazy(() => import('./components/Home')); 
const About = lazy(() => import('./components/About'));
Defines lazy-loaded components. These components will only be loaded when they are rendered for the first time.
const router = createBrowserRouter([ 
  { path: '/', element: <Suspense fallback={<div>Loading...</div>}><Home /></Suspense> }, 
  { path: '/about', element: <Suspense fallback={<div>Loading...</div>}><About /></Suspense> }, 
]);
Creates a router instance with routes. Each route uses Suspense to wrap the lazy-loaded component, showing a fallback while the component loads.
function App() { 
  return <RouterProvider router={router} />; 
}
Defines the main app component that renders the RouterProvider with the created router.