Blog>
Snippets

Code Splitting in SSR with TanStack Router

Explain and demonstrate the process of code splitting in a server-side rendered application using TanStack Router to improve load times and performance.
import { createBrowserRouter, lazy } from 'tanstack-router-dom';
Import necessary functions from tanstack-router-dom. 'lazy' is used for code splitting.
const Dashboard = lazy(() => import('./components/Dashboard'));
Dynamically import the Dashboard component using 'lazy'. This component will only be loaded when it is needed, which is beneficial for performance.
const router = createBrowserRouter([ 
  { path: '/', element: <Home /> }, 
  { path: '/dashboard', element: <Dashboard /> } 
]);
Create the router and define routes. The Dashboard route uses the lazily imported component, enabling code splitting.
const App = () => ( 
  <RouterProvider router={router} /> 
);
Define the App component that uses RouterProvider to enable routing within the application.