Blog>
Snippets

Handling Fallback Content during Asynchronous Component Loading

Provide an example of rendering fallback/loading content while an asynchronously loaded component is being fetched using TanStack Router.
import { createBrowserRouter, RouterProvider, Route } from 'react-router-dom';
Imports necessary functions and components from 'react-router-dom' for routing.
const loader = async () => {
  const module = await import('./SomeComponent');
  return module;
};
Defines a loader function that asynchronously loads 'SomeComponent'.
const router = createBrowserRouter([
  {
    path: '/',
    element: <div>Loading...</div>,
    loader: loader,
    pendingElement: <div>Loading...</div>,
    errorElement: <div>Error loading component</div>
  }
]);
Creates a router instance using 'createBrowserRouter'. Sets up a route configuration with custom loader, and fallback content for pending and error states.
function App() {
  return <RouterProvider router={router} />;
}
Defines the main App component that renders the RouterProvider with the configured router.