Optimizing Initial Load with Preloading Strategies
Showcase how to use TanStack Router's preloading feature to optimize the initial load time of critical components in your application.
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
const router = createBrowserRouter([
{
path: '/',
loader: async () => {
const Home = await import('./Home');
return Home;
}
}
]);
This code snippet creates a router using createBrowserRouter from react-router-dom and defines a route for the root path. The loader function for this route uses dynamic import to asynchronously load the Home component. This is an initial step for optimizing load time by splitting code at the route level.
import { Link, usePreload, useRouteLoaderData } from 'react-router-dom';
function NavLink({ to, children }) {
const preload = usePreload(to);
return (
<Link onMouseEnter={() => preload()} to={to}>
{children}
</Link>
);
}
This code snippet demonstrates how to use the usePreload hook from react-router-dom to preload data for a route when the user hovers over a Link. This Link component wrapper (NavLink) preloads the necessary data for the destination route, reducing load time when the link is actually clicked.
function App() {
const HomeData = useRouteLoaderData('/');
return (
<div>
<NavLink to="/">Home</NavLink>
{/* Use HomeData for rendering or passing to child components */}
</div>
);
}
This code snippet showcases a component that utilizes useRouteLoaderData hook to access preloaded data for a route. In this example, the route loader for '/' would have fetched and preloaded data for the Home component, and this data is then accessible and can be used directly within the App component or passed down to children components, making the component rendering efficient and potentially eliminating the need for additional loading states.