Next.js - useParams() Function



The useParams() Function

The Next.js useParams() function is used to access dynamic route parameters filled in route segments. This function is only available in the client-side.

Syntax

The syntax for the useParams() function is as follows:

'use client'

import { useParams } from 'next/navigation';

const params = useParams();

// If URL is /users/123
console.log(params); // Output: { id: '123' }

Parameters

The useParams() function does not accept any parameters.

Return Value

The useParams() returns an object containing the current route's filled in dynamic parameters. The object keys are the parameter names, and the values are the parameter values. For example,

Route URL useParams()
app/shop/page.js /shop {}
app/shop/[slug]/page.js /shop/1 { slug: '1' }
app/shop/[tag]/[item]/page.js /shop/1/2 { tag: '1', item: '2' }
app/shop/[...slug]/page.js /shop/1/2 { slug: ['1', '2'] }

Example 1

In the example below, we are using the useParams() function to access the dynamic parameters of the current route and display them in the console.

'use client'
 
import { useParams } from 'next/navigation'
 
export default function ExampleClientComponent() {
  const params = useParams()
 
  // Route -> /shop/[tag]/[item]
  // URL -> /shop/shoes/nike-air-max-97
  // `params` -> { tag: 'shoes', item: 'nike-air-max-97' }
  console.log(params)
 
  return <h1>Next.js useParams Function</h1>
}

Example 2

In the example below, we used the useParams() function to access parameters of route and displayed them in the current page itself.

'use client';
import { useParams } from 'next/navigation';

export default function ProductPage() {
  const params = useParams();
  
  // For URL: /products/123/reviews/456
  console.log(params); // { productId: '123', reviewId: '456' }
  
  return (
        <div>
            <h1>Product ID: {params.productId}</h1>
            <h2>Review ID: {params.reviewId}</h2>
        </div>
  );
}
Advertisements