Preloading Data with TanStack Router
Demonstrate how to preload necessary data for a route before completing navigation, ensuring a smoother user experience.
import { createBrowserRouter, RouterProvider } from 'tanstack-router';
import { queryClient, postsQueryKey, fetchPosts } from './myQueries';
This imports the necessary functionality from `tanstack-router` and also imports a custom queryClient, a queryKey, and a data fetching function from a module that manages data queries.
const preloadPostsData = async () => {
await queryClient.prefetchQuery(postsQueryKey, fetchPosts);
};
Defines a function to preload the data. This function uses `queryClient.prefetchQuery` to fetch and cache the posts data before navigating to the route where it's needed.
const router = createBrowserRouter([
{
path: '/posts',
loader: preloadPostsData,
element: () => import('./PostsPage'),
},
]);
Creates a new router instance, setting up a route to `/posts`. It uses the `loader` property to call `preloadPostsData` function before navigating to the `/posts` path, ensuring the data is preloaded.
function App() {
return <RouterProvider router={router} />;
}
Defines the main App component. This component renders the `RouterProvider` from tanstack-router, passing the `router` instance we created as its prop, which enables routing in our application.