Blog>
Snippets

Route Preloading with TanStack Router

Shows how to preload data or components for routes in TanStack Router, enhancing user experience by reducing load times.
import { createBrowserRouter, RouterProvider } from 'tanstack-router';

// Define a loader function to preload data for the route
const dashboardLoader = async () => {
  const data = await fetchDataForDashboard();
  return data;
};

// Create a router instance with routes using the loader
const router = createBrowserRouter([
  {
    path: '/dashboard',
    loader: dashboardLoader, // Attaching the loader to the route
    element: <Dashboard />,
  },
]);
This code snippet demonstrates how to create a router instance with TanStack Router and define a loader function for preloading data for a specific route (e.g., '/dashboard'). The loader function 'dashboardLoader' fetches data asynchronously that will be preloaded whenever the '/dashboard' route is matched.
import { useMatch } from 'tanstack-router';

function Dashboard() {
  const match = useMatch();
  
  // Access preloaded data in the component
  const data = match.data;
  
  return (
    // Render your component using the preloaded data
  );
}
This snippet shows how to use the 'useMatch' hook inside the Dashboard component to access the preloaded data provided by the loader function assigned to the '/dashboard' route. The 'data' obtained from 'useMatch()' can then be used to render the Dashboard component.
import React from 'react';
import { RouterProvider } from 'tanstack-router';

function App() {
  // Render the router with the RouterProvider
  return <RouterProvider router={router} />;
}
This example illustrates the final step in setting up Route Preloading with TanStack Router, showing how to render the router within the application using the 'RouterProvider'. Here, 'router' refers to the router instance created earlier, configured with routes that include preloading functionalities.