Blog>
Snippets

Implementing Dynamic Routes with useParams Hook

Provide an example of how to create dynamic routes using TanStack Router, including the use of the useParams hook to fetch and display data based on URL parameters.
import { createBrowserRouter, RouterProvider, Route, useParams } from '@tanstack/react-router';
import React from 'react';
import UserProfile from './UserProfile';

// Define routes
const router = createBrowserRouter([
  {
    path: '/user/:userId',
    element: <UserProfile />,
  },
]);

// Render the router with RouterProvider
function App() {
  return <RouterProvider router={router} />;
}
This code snippet demonstrates the setup of a dynamic route using TanStack Router. It defines a route where ':userId' is a dynamic segment. The `UserProfile` component will render when the route matches '/user/:userId'.
import React from 'react';
import { useParams } from '@tanstack/react-router';

function UserProfile() {
  const params = useParams();
  const userId = params.userId;

  // Fetch and display user data based on userId

  return (
    <div>
      <h1>User Profile: {userId}</h1>
      {/* Display user details here */}
    </div>
  );
}
This component uses the `useParams` hook to extract the dynamic segment 'userId' from the URL path. It then uses this ID to potentially fetch and display the user's profile data.