Blog>
Snippets

Code-Splitting and Lazy Loading with TanStack Router

Illustrate how to use code-splitting and lazy loading features in TanStack Router to optimize the performance of a JavaScript application.
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import React from 'react';
Import necessary modules from 'react-router-dom' and 'react' to set up the router and enable lazy loading.
const Home = React.lazy(() => import('./components/Home'));
const About = React.lazy(() => import('./components/About'));
Define lazily loaded components using React.lazy for Home and About pages. These components will be loaded only when needed.
const router = createBrowserRouter([
  { path: '/', element: <Home /> },
  { path: '/about', element: <About /> }
]);
Create a browser router and define routes using lazily loaded components. Each route is associated with a component.
function App() {
  return <RouterProvider router={router} />;
}
Define the App component that utilizes RouterProvider for routing control within the application.