Blog>
Snippets

Defining Loaders for Async Data Fetching with TanStack Router

Show how to define a loader function within a route to fetch data asynchronously, utilizing the `defer` property for optimized loading.
import { createBrowserRouter, defer } from 'react-router-dom';
import { fetchUserData } from './api/user';
Imports necessary functions and utilities from React Router and a hypothetical API module for data fetching.
const userLoader = async ({ params }) => {
  const userData = fetchUserData(params.userId);
  return defer({ userData });
};
Defines an asynchronous loader function for fetching user data. The defer property is used to enable optimized loading, allowing the rest of the route to render while data is still being fetched.
const router = createBrowserRouter([
  {
    path: '/user/:userId',
    loader: userLoader,
    element: <UserPage />
  }
]);
Creates a router instance, defining a route that uses the userLoader to fetch data asynchronously. The loader is associated with a specific route path, and the element property specifies the component to render when the path matches.