Blog>
Snippets

Lazy Loading Components with TanStack Router

Provide an example of how to lazily load components in routes to optimize performance and speed up initial application load.
import { lazy, Suspense } from 'react';
First, import lazy and Suspense from React to enable lazy loading and handling of the loading state.
const LazyComponent = lazy(() => import('./LazyComponent'));
Define a lazy component using React.lazy(), which dynamically imports the component. This means the component will only be loaded when it's needed.
const router = createBrowserRouter([
  {
    path: '/lazy',
    element: (
      <Suspense fallback={<div>Loading...</div>}>
        <LazyComponent />
      </Suspense>
    ),
  },
]);
Configure TanStack Router with a route for the lazy component. Wrap the LazyComponent with Suspense and provide a fallback UI to display while the component is being loaded.