Blog>
Snippets

Tracking Route State Changes

Demonstrate using TanStack Router Devtools to track and log state changes as the user navigates through the application, focusing on state preservation and debugging.
import { createBrowserRouter, RouterProvider } from '@tanstack/react-router';
import { DevTools } from '@tanstack/router-devtools';
Imports necessary components from TanStack's React Router and the Router DevTools for development.
const router = createBrowserRouter([
  // Define your route objects here
]);
Creates a new router instance using the `createBrowserRouter` function.
function App() {
  return (
    <RouterProvider router={router} /> // Provides the router context to the application
  );
}
Defines the main App component that renders the RouterProvider with the created router.
if (process.env.NODE_ENV === 'development') {
  DevTools.getInstance().then(devTools => {
    router.subscribe(() => {
      // Log current state whenever there is a navigation change
      console.log('Current state:', devTools.getState());
    });
  });
}
Subscribes to router changes and logs the current state for debugging purposes, conditional on being in development environment. Utilizes the `subscribe` method of the router instance to listen for navigation changes and the `DevTools` instance to access and log the current router state.