Blog>
Snippets

Optimizing Asynchronous Blocking for Performance

Showcase how to implement asynchronous navigation blocking with TanStack Router, ensuring minimal performance impact when performing API calls for navigation verification.
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import { checkAuth } from './api/auth'; // Mock API call for authentication check

const router = createBrowserRouter([
  {
    path: '/',
    element: <HomePage />,
    loader: async () => {
      // Perform API call before navigation
      const isAuthenticated = await checkAuth();
      if (!isAuthenticated) {
        throw new Response(null, { status: 403 });
      }
    },
  },
]);
This code snippet showcases how to implement asynchronous navigation blocking with TanStack Router (previously known as React Router). It uses the `createBrowserRouter` to configure a route for the home page (`/`). The `loader` property leverages an async function to perform an API call checking for authentication (`checkAuth`). If the user is not authenticated, it throws an error preventing the navigation, thus minimizing the performance impact by avoiding unnecessary component rendering.