Using Nested Routes with Code Splitting in TanStack Router
Illustrate the setup of nested routes with code splitting, emphasizing the organization and optimization of component structures in a complex application.
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import { lazy } from 'react';
// Using React.lazy to code split components
const Home = lazy(() => import('./components/Home'));
const About = lazy(() => import('./components/About'));
const Post = lazy(() => import('./components/posts/Post'));
const PostDetails = lazy(() => import('./components/posts/PostDetails'));
// Create a router instance
const router = createBrowserRouter([
{
path: '/',
element: <Home />,
children: [
{ path: 'about', element: <About /> },
{
path: 'posts',
element: <Post />, // Lazy load Posts component
children: [
// Nested route with lazy loaded PostDetails component
{ path: ':postId', element: <PostDetails /> }
]
}
]
}
]);
function App() {
return <RouterProvider router={router} />;
}
This code snippet demonstrates how to set up nested routes with code-splitting in TanStack Router. It uses `React.lazy` for lazy loading components to optimize loading times. `Home`, `About`, `Post`, and `PostDetails` components are loaded on demand. The router is configured with a base route and nested routes for 'about' and 'posts', where 'posts' itself has a nested route for post details.