Blog>
Snippets

Lazy Loading Modules with TanStack Router

Example of defining lazy-loaded routes in TanStack Router to split code by route and reduce initial load time.
import { createBrowserRouter, createRoutesFromElements, Route } from 'react-router-dom';
import { createLazyFileRoute } from 'tanstack-router';
Imports the necessary functions from 'react-router-dom' and the 'createLazyFileRoute' from 'tanstack-router'.
// Lazy load a component
const LazyHomePage = createLazyFileRoute(() => import('./pages/HomePage.lazy.tsx'), {
  // Provide a fallback component (optional)
  fallback: <div>Loading...</div>
});
Defines a lazy-loaded route for the HomePage. The 'createLazyFileRoute' function takes a dynamic import statement and an optional fallback component to display while loading.
const router = createBrowserRouter(
  createRoutesFromElements(
    <Route path="/" element={<LazyHomePage />} />
  )
);
Creates a router using 'createBrowserRouter' and 'createRoutesFromElements'. Defines a route path that uses the lazy-loaded HomePage component.