Lazy Loading with React.Suspense in TanStack Router
Illustrate how to use React.Suspense in combination with TanStack Router for lazy loading components at different levels of the route tree, to improve performance.
import { createBrowserRouter, RouterProvider } from 'tanstack-router';
import React from 'react';
Import necessary components from TanStack Router and React.
const Home = React.lazy(() => import('./Home'));
Define a lazy-loaded Home component using React.lazy.
const About = React.lazy(() => import('./About'));
Define a lazy-loaded About component using React.lazy.
const router = createBrowserRouter([
{
path: '/',
element: <React.Suspense fallback={<div>Loading...</div>}><Home /></React.Suspense>,
},
{
path: '/about',
element: <React.Suspense fallback={<div>Loading...</div>}><About /></React.Suspense>,
},
]);
Create a router instance with routes. Each route element is wrapped in React.Suspense to handle the loading state.
function App() {
return <RouterProvider router={router} />;
}
Define the App component that utilizes the RouterProvider with the configured router.