Blog>
Snippets

Leveraging TanStack Router's useNavigate for Programmatic Navigation

Demonstrate how to use the useNavigate hook for programmatic navigation within a TanStack Router-based application, including examples of navigating back or to a specific route with parameters.
import { useNavigate } from 'tanstack-router';

function NavigationComponent() {
  const navigate = useNavigate();

  // Navigating to a specific route
  function goToAbout() {
    navigate('/about');
  }

  // Navigating with parameters
  function goToUserProfile(userId) {
    navigate(`/users/${userId}`);
  }

  // Navigating back
  function goBack() {
    navigate(-1);
  }

  return (
    <div>
      <button onClick={goToAbout}>Go to About Page</button>
      <button onClick={() => goToUserProfile('123')}>Go to User Profile</button>
      <button onClick={goBack}>Go Back</button>
    </div>
  );
}
This example demonstrates how to use the useNavigate hook from TanStack Router for programmatic navigation within a React component. It includes examples of navigating to a particular route, to a route with parameters, and going back in the browser history.