Blog>
Snippets

Basic Implementation of Code Splitting in TanStack Router

Demonstrate how to implement basic code splitting in a JavaScript application using TanStack Router with dynamic import and React.lazy.
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import React from 'react';
const Home = React.lazy(() => import('./Home'));
const About = React.lazy(() => import('./About'));

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>,
    },
]);

function App() {
    return <RouterProvider router={router} />;
}
This code demonstrates the setup of a basic TanStack Router with code splitting for a React application. It first imports necessary functions from react-router-dom and React itself. Two routes are defined: Home and About, each lazily loaded using React's lazy() function; this means their respective components are only fetched when needed. The RouterProvider component is then used to apply the router configuration containing our lazily loaded routes. This setup utilizes React's Suspense component to show a loading fallback while the route components are being loaded.