Basic Route Preloading with TanStack Router
Show how to preload data for a specific route when the user hovers over a link, using TanStack Router's `onMouseEnter` event to trigger data fetching.
import { useMatch, Link } from '@tanstack/react-location';
Import necessary hooks and components from TanStack Router.
function preloadRouteData(routePath) {
// Define a function to preload your data
// This might be fetching data from an API or preloading a code-split component
console.log(`Preloading data for ${routePath}`);
}
Define a function for preloading data for a specific route. This function simulates data preloading by logging a message to the console.
function PreloadLink({ to, children }) {
const match = useMatch();
const handleMouseEnter = () => {
// Preload the data for the route on mouse enter
if (match.route.path !== to) { // To prevent preloading for the current route
preloadRouteData(to);
}
};
return (
<Link to={to} onMouseEnter={handleMouseEnter}>
{children}
</Link>
);
}
Create a custom link component that preloads data when the user hovers over it. The component uses `useMatch` to prevent preloading data for the current route.
function App() {
return (
<div>
<h1>Welcome to Our Site</h1>
<nav>
<PreloadLink to="/about">About Us</PreloadLink>
<PreloadLink to="/contact">Contact</PreloadLink>
</nav>
</div>
);
}
Define the main application component. It renders a simple webpage with navigation links that use the `PreloadLink` component to enable route data preloading on hover.