Blog>
Snippets

Implementing `useMatchPreload` for Preloading Data

A practical demonstration of using `useMatchPreload` hook with TanStack Router to preload data for anticipated navigation, improving load times and user experience.
import { useMatchPreload } from '@tanstack/react-location';

function MyComponent() {
  // Using the useMatchPreload hook to create a preload function
  const preloadArticle = useMatchPreload({
    to: '/next-article',
    search: '?preload=true'
  });

  return (
    <div>
      <a
        href="/next-article"
        onMouseEnter={() => preloadArticle()}
        // Preload the data when the user hovers over this link
      >
        Next Article
      </a>
    </div>
  );
}
This code snippet demonstrates how to use the `useMatchPreload` hook from '@tanstack/react-location' to preload data for a route when the user hovers over a link to '/next-article'. The `preloadArticle` function is created using `useMatchPreload` with the specified path and query parameters, and is triggered by the `onMouseEnter` event on the anchor tag.