Blog>
Snippets

Implementing Priority-based Resource Preloading

Illustrate prioritizing the preloading of resources based on their importance to the user's current context/navigational path, using TanStack Router's dynamic import capabilities.
import { createBrowserRouter, RouterProvider } from 'react-router-dom';

// Define your routes
const router = createBrowserRouter([
  {
    path: '/',
    element: React.lazy(() => import('./Home')), // Home page, high priority
    loader: () => fetchImportantDataForHome(), // Preload important data for home
    children: [
      {
        path: 'detail',
        element: React.lazy(() => import('./Detail')), // Detail page, next priority
        loader: () => fetchDetailData(), // Preload data for detail page
      },
      {
        path: 'profile',
        element: React.lazy(() => import('./Profile')), // Profile, lower priority
        // No preload as it's considered lower priority
      }
    ]
  }
]);
This snippet creates a router with prioritized resource loading. The Home component is loaded first, with important data pre-fetched. Detail component is the next priority with its data pre-fetched. Profile is considered lower priority, loaded lazily without pre-fetching data.