Blog>
Snippets

Dynamic Loading with TanStack Router

Illustrate how to dynamically load components based on the active route using TanStack Router, improving SPA performance through lazy loading techniques.
import { lazy, Suspense } from 'react';
import { createBrowserRouter, RouterProvider } from 'tanstack/react-router';

// Define lazy-loaded components
const LazyUserProfile = lazy(() => import('./components/UserProfile'));
const LazyUserSettings = lazy(() => import('./components/UserSettings'));
const LazyUserPosts = lazy(() => import('./components/UserPosts'));

// Define routes with dynamic loading
const router = createBrowserRouter([
  {
    path: '/',
    element: (
      <Suspense fallback={<div>Loading...</div>}>
        <LazyUserProfile />
      </Suspense>
    ),
  },
  {
    path: 'settings',
    element: (
      <Suspense fallback={<div>Loading...</div>}>
        <LazyUserSettings />
      </Suspense>
    ),
  },
  {
    path: 'posts',
    element: (
      <Suspense fallback={<div>Loading...</div>}>
        <LazyUserPosts />
      </Suspense>
    ),
  },
]);
This code snippet initializes TanStack Router for a React application, defining routes for 'UserProfile', 'UserSettings', and 'UserPosts'. It leverages React's 'lazy' and 'Suspense' for dynamic component loading based on the route. Each route's element is wrapped in a Suspense component with a fallback loading state, ensuring the component for the current route is loaded asynchronously only when necessary, improving performance.