Integrating TanStack Query with TanStack Router
Illustrate a pattern for integrating TanStack Query with TanStack Router for managing complex data dependencies and improving UX with background data fetching.
import { createBrowserRouter, RouterProvider } from 'tanstack-router-dom';
import { QueryClient, QueryClientProvider } from 'tanstack-query-core';
import { ReactQueryDevtools } from 'tanstack-query-devtools';
import Posts from './components/Posts';
// Initialize TanStack Query Client
const queryClient = new QueryClient();
// Define Routes
const router = createBrowserRouter([
{
path: '/',
element: <Posts />,
loader: async () => ({
posts: await fetchPosts()
})
}
]);
// App component
function App() {
return (
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
);
}
export default App;
This code snippet demonstrates how to integrate TanStack Query with TanStack Router in a React application. It initializes the TanStack Query client and sets up a basic router with a single route. The route uses a loader function to fetch data (using a hypothetical fetchPosts function) before rendering the Posts component. The App component wraps the RouterProvider and QueryClientProvider around the application's components, enabling global access to routing and state management features. The ReactQueryDevtools component is also incorporated for debugging purposes.