Blog>
Snippets

Initializing TanStack Router in a JavaScript Application

Demonstrate how to set up TanStack Router in a JavaScript application, including the basic configuration and route definitions necessary for deferred data loading.
import { createBrowserRouter, RouterProvider, defer } from 'react-router-dom';
import { Root, Contacts, Contact } from './components';

// Define your loaders
const contactLoader = async ({ params }) => {
  const contactDetails = await fetchContactDetails(params.contactId);
  return defer({ contactDetails });
};

// Create the router instance
const router = createBrowserRouter([
  {
    path: '/',
    element: <Root />,
    children: [
      {
        path: 'contacts',
        element: <Contacts />,
        children: [
          {
            path: 'contacts/:contactId',
            element: <Contact />,
            loader: contactLoader
          }
        ]
      }
    ]
  }
]);
This snippet initializes the TanStack Router (formerly known as React Router) with a root route and a nested route for 'contacts'. Each contact detail route has a loader function that fetches data using the defer method to enable deferred data loading.
import { createRoot } from 'react-dom/client';

const container = document.getElementById('app');
const root = createRoot(container);

root.render(<RouterProvider router={router} />);
This code mounts the TanStack Router to the DOM using React 18's createRoot API, making the RouterProvider the root component of your app. It demonstrates how to render the router setup in your application.