Blog>
Snippets

Lazy Loading Components for Authenticated Routes

Illustrate how to implement lazy loading for React components that are rendered in authenticated routes using TanStack Router.
import { createBrowserRouter, RouterProvider } from '@tanstack/react-router';
import React from 'react';

// AuthWrapper checks if user is authenticated
import { AuthWrapper } from './components/AuthWrapper';

// Lazy loading the Dashboard component
const Dashboard = React.lazy(() => import('./components/Dashboard'));

// Creating the router instance
const router = createBrowserRouter([
    {
        path: '/',
        element: <AuthWrapper><React.Suspense fallback={<div>Loading...</div>}><Dashboard /></React.Suspense></AuthWrapper>,
    },
]);
This code snippet first imports necessary functions and React itself. Then, it imports an AuthWrapper component that contains logic to verify user authentication. The Dashboard component is setup for lazy loading using React.lazy for improved performance, only loading when needed. A router instance is created using createBrowserRouter which includes a path setup for an authenticated Dashboard route. The Dashboard is wrapped with the AuthWrapper to ensure authentication, and React.Suspense is used to handle the lazy loading with a fallback loading indicator.