Blog>
Snippets

Lazy Loading Components Based on Path Params

Illustrate lazy loading of JavaScript components in a TanStack Router setup based on the value of path params, improving performance by loading resources only when necessary.
import { createBrowserRouter, RouterProvider, Route } from 'react-router-dom';
import React, { lazy, Suspense } from 'react';
const LazyComponent = lazy(() => import('./LazyComponent'));

const router = createBrowserRouter([
    {
        path: 'home',
        element: <div>Home Page</div>,
    },
    {
        path: 'feature/:featureId',
        element: (
            <Suspense fallback={<div>Loading...</div>}>
                <LazyComponent />
            </Suspense>
        ),
    },
]);
This code snippet creates a router with TanStack Router in a React application, featuring lazy loading for a component based on path parameters. The `LazyComponent` is only loaded when the user navigates to the 'feature/:featureId' route, improving performance by loading resources only when necessary. The `Suspense` component from React is used to display a loading state until the lazy-loaded component is ready.