Blog>
Snippets

Prefetching Data with TanStack Router

Illustrate how to prefetch data for upcoming navigations in a SPA using TanStack Router, reducing wait times for data loading.
import { useMatch, useLoaderData } from 'tanstack-router';
Import necessary hooks from TanStack Router.
function prefetchData() {
  const match = useMatch(); // Use the useMatch hook to get details about the route match
  const prefetch = async () => {
    if (match) {
      const data = await fetch(match.route.dataPath).then(res => res.json());
      // Logic to cache fetched data
    }
  };
  prefetch();
}
Define a function to prefetch data based on the route being navigated to. This involves checking if there's a match for a route and then fetching the data from a specified endpoint. The fetched data should then be cached for future use.
function App() {
  const data = useLoaderData(); // Use useLoaderData hook to access data loaded for the route
  // Render app or components using prefetched data
}
In your application component, use the useLoaderData hook to access data that was loaded for the route, including prefetched data. This approach ensures that data is ready by the time the component needs it, reducing wait times and improving user experience.