tezvyn:

useParams: Accessing Dynamic URL Segments

AI-drafted, machine-checkedSource: nextjs.orgintermediate

The `useParams` hook lets client components read dynamic URL segments. On a route like `/posts/[slug]`, it returns an object like `{ slug: 'my-post' }`. Remember, it's for client components only and won't see query strings.

WHY IT EXISTS: Web apps need to display content based on the URL. For dynamic pages, like a user profile or a product detail page, a unique identifier is often part of the URL path itself. We need a way to access this identifier from within our components to fetch and display the correct data.

THE MENTAL MODEL: Think of useParams as a client-side listener for the URL's "wildcard" sections. You define placeholders in your folder structure (e.g., app/posts/[slug]/page.js), and useParams lets your component code read whatever value fills that placeholder in the user's browser.

HOW IT WORKS: In a Next.js App Router project, you first define a dynamic segment by naming a folder with brackets, like [id]. Inside a client component (marked with "use client"), you import useParams from next/navigation. Calling const params = useParams() returns an object where keys correspond to your dynamic segment names and values are the actual segments from the current URL. For a URL like /users/42, params would be { id: '42' }. The values are always strings.

WHEN TO USE IT: Use useParams inside any Client Component that needs to know the dynamic parts of the current URL path. This is common for fetching data on the client side based on an ID, setting active states in navigation, or rendering titles and headers that include the dynamic segment.

WHEN NOT TO USE IT: The primary footgun is trying to use it in a Server Component. Server Components don't use hooks for this; they receive params directly as page props (e.g., function Page({ params })). Also, do not use useParams to get query string parameters (the part after ?). For that, use the useSearchParams hook instead.

ONE CANONICAL EXAMPLE: To build a user profile page at /profile/[username], you would create a file at app/profile/[username]/page.jsx. The component would look like this: 'use client'; import { useParams } from 'next/navigation'; export default function ProfilePage() { const params = useParams(); return <h1>Profile for {params.username}</h1>; } If the URL is /profile/jane-doe, this component renders a heading with "Profile for jane-doe".

Read the original → nextjs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.