Blog>
Snippets

Preloading Data with TanStack Router's Loader Function

Show how to use the loader function of TanStack Router to preload data before the component mounts, ensuring the data is readily available upon component render.
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import { queryClient } from './queryClient'; // assuming you've set up a TanStack QueryClient
import { fetchData } from './api'; // your data fetching function
Imports necessary libraries and functions. We're assuming that `queryClient` is your instance of TanStack Query Client, and `fetchData` is a function to fetch data from an API.
const loader = async () => {
  const data = await fetchData();
  return data;
};
Defines the loader function that fetches data asynchronously. This data will be preloaded by the TanStack Router.
const route = {
  path: '/example',
  loader: loader,
  element: <YourComponent />
};
Sets up a route object with a path, the loader function defined earlier, and the component that will use the preloaded data.
const router = createBrowserRouter([
  route
]);
Creates a router instance with the TanStack Router, passing in an array of route objects. In this case, we're only passing in the single route we've created.
<RouterProvider router={router} />
Finally, we use the RouterProvider component from TanStack Router to apply our router configuration to our app. This component should be placed at the root of your component tree.