Blog>
Snippets

Improving SSR Performance with TanStack Router

Implement caching strategies and optimize render performance in an SSR application using TanStack Router, focusing on reducing server response times.
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import Home from './components/Home';
import ProductDetail from './components/ProductDetail';

// Initialize QueryClient with default caching strategies
const queryClient = new QueryClient();

// Define routes including component prefetching
const router = createBrowserRouter([
  {
    path: '/',
    element: <Home />, // Home component
    loader: async () => ({
      products: await fetchProducts() // Prefetch products for home page
    })
  },
  {
    path: '/product/:productId',
    element: <ProductDetail />, // ProductDetail component
    loader: async ({ params }) => ({
      product: await fetchProduct(params.productId) // Prefetch product details
    })
  }
]);
This code initializes a QueryClient for caching and prefetches data in the route definitions using TanStack's React Router and React Query. Each route definition includes a loader function for prefetching necessary data, improving SSR performance by reducing the number of server round trips.
function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <RouterProvider router={router} />
    </QueryClientProvider>
  );
}
Sets up the application with a QueryClientProvider and RouterProvider, ensuring that routing and data fetching logic using TanStack Router and React Query are integrated throughout the app.