Blog>
Snippets

Optimizing Application Performance with Code Splitting in TanStack Router

Explain code splitting within the context of TanStack Router for file-based routing, demonstrating how to asynchronously load components based on the route for improved performance.
import { createBrowserRouter, createRoutesFromElements, Route } from 'react-router-dom';
Imports necessary functions and components from the react-router-dom package, which is required to set up routing for the application.
const lazyLoadComponent = (path) => lazy(() => import(path));
Defines a helper function to asynchronously load components using React's lazy function. This function takes a path to the component file and returns a lazy-loaded component.
const router = createBrowserRouter(createRoutesFromElements(
  <Route path="/" element={<App />}/>,
  <Route path="/about" element={lazyLoadComponent('./AboutPage.lazy.tsx')}/>
));
Creates a browser router using `createBrowserRouter` and sets up routes using `createRoutesFromElements`. The route for the About page uses the helper function `lazyLoadComponent` to load the component asynchronously. This way, the AboutPage component is not loaded until the user navigates to the About route, improving initial load performance.
export default router;
Exports the configured router for use in the application.