Blog>
Snippets

Navigating Programmatically with TanStack Router while Preserving Type Safety

Show how to navigate between components programmatically using TanStack Router, emphasizing how it preserves type safety and application state across navigations.
import { useNavigate } from 'tanstack-router';

function NavigateToProfile() {
  const navigate = useNavigate();
  
  function handleClick() {
    // Navigate to the /profile route programmatically.
    // Ensuring type safety by defining expected query parameter types.
    navigate({
      to: '/profile',
      search: { userId: '123' }
    });
  }
  
  return (
    <button onClick={handleClick}>Go to Profile</button>
  );
}
This code demonstrates how to navigate programmatically to a different route using TanStack Router's useNavigate hook, with a focus on preserving type safety for search parameters. The navigate function is used to change the route to '/profile' while passing a userId as a search parameter, ensuring that the navigation is not only programmatic but also typesafe.
import { createBrowserRouter, RouterProvider, Route } from 'tanstack-router';

const router = createBrowserRouter([
  {
    path: '/',
    element: <Home />
  },
  {
    path: '/profile',
    element: <Profile />
    // Using loader to manage state and fetch data based on search params
    loader: async ({ params, search }) => {
      const userId = search.userId;
      // Fetch user data based on userId
      const userData = await fetchUserData(userId);
      return { userData };
    }
  }
]);

function App() {
  return <RouterProvider router={router} />;
}
This code snippet sets up routing for a React application using TanStack Router, including a route to the Profile component that utilizes a loader function. The loader function demonstrates how to safely handle search parameters (like userId) to fetch and return user data, showing how TanStack Router preserves type safety and application state across navigations by incorporating search params validation and asynchronous data fetching.