Blog>
Snippets

Client-side Navigation with Dynamic Routes

Use the useRouter hook to show how to navigate to dynamic routes programmatically on the client-side, including how to construct the route string with dynamic segments.
import { useRouter } from 'next/router';

function navigateToProfile() {
  const router = useRouter();

  // Example user id you want to navigate to
  const userId = '123';

  // Construct the dynamic route, assuming the path is /users/[id]
  const href = `/users/${userId}`;

  // Programmatic navigation to the dynamic route
  router.push(href);
}

// Trigger navigation within a component, using onClick or similar event
//<button onClick={navigateToProfile}>Go to Profile</button>
This code demonstrates how to use the useRouter hook from Next.js to perform client-side navigation to a dynamic route. The navigateToProfile function uses useRouter to push a new route with a dynamic segment representing a user's ID to the history stack, allowing navigation to that specific user's profile page without a full page refresh. The dynamic route string is constructed using template literals and then passed to the router.push method. Finally, an example button is shown (as a comment) that, when clicked, would trigger the navigation.