Blog>
Snippets

Implementing Lazy Loading for Images with TanStack Router

Show how to defer the loading of images in a SPA until they are needed using TanStack Router, improving initial load times.
import { lazy, Suspense } from 'react';
import { Route } from 'tanstack/react-location';

const LazyImageComponent = lazy(() => import('./LazyImageComponent'));

export const routes = [
  {
    path: '/lazy-image',
    element: (
      <Suspense fallback={<div>Loading image...</div>}>
        <LazyImageComponent />
      </Suspense>
    ),
  },
];
This code snippet demonstrates the setup for lazy loading an image component using TanStack Router. The 'lazy' import from React allows the component to be loaded only when needed. The 'Suspense' component is used to show a fallback while waiting for the LazyImageComponent to load. Finally, the route is defined where this lazy loading occurs, with '/lazy-image' being the path where the component will be rendered.
import React from 'react';

function LazyImageComponent() {
  return (
    <img src='path/to/your/image.jpg' alt='Lazy Loaded Image' />
  );
}

export default LazyImageComponent;
This code snippet represents the LazyImageComponent that gets dynamically loaded. It is a simple React component that renders an image. Replace 'path/to/your/image.jpg' with the actual path to the image you want to lazy load. This component will only be loaded and rendered in the application when the specific route (/lazy-image) is accessed, thanks to the lazy loading setup with TanStack Router and React.