Skip to content
The Chat Archive
gemini-2.5-flash· Google LMArena Human Preference 140K

tell me abour use params in next js and set it on url

  1. User

    tell me abour use params in next js and set it on url

  2. Assistant

    In Next.js's App Router (introduced in Next.js 13), useParams is a powerful React Hook that allows you to access the dynamic segments of the current URL. These dynamic segments are defined by your folder structure.

    Let's break down what useParams is, how it works, and how parameters are set in the URL through Next.js's routing conventions.


    What is useParams?

    useParams is a hook provided by next/navigation that gives you an object containing the dynamic parameters from the URL.

    • Purpose: To read the values of dynamic URL segments (e.g., [id], [slug]) in your components.
    • Availability: It's exclusively available in the App Router. If you're using the older Pages Router, you'd typically use useRouter().query instead.
    • Component Type: useParams must be used in a Client Component. This is because it needs access to the browser's URL, which is a client-side concept.

    How Parameters are "Set" on the URL (and defined in Next.js)

    You don't directly "set" parameters in the URL using useParams. Instead, Next.js defines URL parameters via its file-system based routing. When a user navigates to a URL that matches your dynamic route, Next.js automatically populates the useParams object with the corresponding values.

    Defining Dynamic Segments (Folder Structure)

    To define a dynamic parameter, you use square brackets [] around a folder name.

    Example:

    If you want a route like /blog/my-first-post, where my-first-post is a dynamic value (the "slug"), your folder structure would look like this:

    app/
    └── blog/
        └── [slug]/
            └── page.tsx
    

    In this structure:

    • blog is a static segment.
    • [slug] is a dynamic segment. Whatever value appears in place of [slug] in the URL will be available as slug in your useParams object.
    • page.tsx is the component rendered for this route.

    How to Use useParams

    1. Import useParams: From next/navigation.
    2. Mark as Client Component: Add 'use client'; at the top of your file.
    3. Call useParams(): Inside your component.
    4. Access Parameters: The returned object will have keys matching your dynamic segment names.

    Practical Example

    Let's say you have a blog where each post has a unique slug.

    1. Define the Route:

    app/blog/[slug]/page.tsx

    // app/blog/[slug]/page.tsx
    'use client'; // This component needs to be a Client Component
    
    import { useParams } from 'next/navigation'; // Import the hook
    
    export default function BlogPostPage() {
      const params = useParams(); // Call the hook
    
      // params will be an object like { slug: 'my-first-post' }
      const { slug } = params; // Destructure the slug from params
    
      return (
        <div style={{ padding: '20px', border: '1px solid #ccc', borderRadius: '8px' }}>
          <h1>Blog Post Details</h1>
          <p>You are viewing the post with slug: <strong>{slug}</strong></p>
          <p>This content would typically be fetched based on this slug.</p>
          <p>For example, a fetch to `/api/posts/${slug}`</p>
        </div>
      );
    }
    

    2. How it works with URLs:

    • URL: http://localhost:3000/blog/my-first-post

      • useParams() will return: { slug: 'my-first-post' }
      • Output: "You are viewing the post with slug: my-first-post"
    • URL: http://localhost:3000/blog/nextjs-getting-started

      • useParams() will return: { slug: 'nextjs-getting-started' }
      • Output: "You are viewing the post with slug: nextjs-getting-started"

    Important Considerations

    1. Client Components Only ('use client';)

    As mentioned, useParams needs to run in the browser to access the URL. Always remember to add 'use client'; at the top of any file using useParams.

    2. Type Safety with TypeScript

    By default, useParams returns Readonly<Record<string, string | string[]>>. For better type safety, you can specify the expected type:

    // For a single dynamic segment
    import { useParams } from 'next/navigation';
    
    interface Params {
      slug: string;
      // If you had more params:
      // category: string;
    }
    
    export default function BlogPostPage() {
      const params = useParams<Params>();
      const { slug } = params;
      // ...
    }
    

    3. Multiple Parameters

    You can have multiple dynamic segments in a path:

    Route: app/[category]/[product]/page.tsx

    Component:

    // app/[category]/[product]/page.tsx
    'use client';
    import { useParams } from 'next/navigation';
    
    interface ProductParams {
      category: string;
      product: string;
    }
    
    export default function ProductPage() {
      const params = useParams<ProductParams>();
      const { category, product } = params;
    
      return (
        <div>
          <h1>Product Details</h1>
          <p>Category: {category}</p>
          <p>Product: {product}</p>
        </div>
      );
    }
    

    URL Example: /electronics/laptop

    • params will be { category: 'electronics', product: 'laptop' }

    4. Catch-all Segments ([...slug])

    If you need to match arbitrary deep paths, use [...slug]. The value will be an array of strings.

    Route: app/docs/[...slug]/page.tsx

    Component:

    // app/docs/[...slug]/page.tsx
    'use client';
    import { useParams } from 'next/navigation';
    
    interface DocsParams {
      slug: string[]; // slug will be an array of strings
    }
    
    export default function DocsPage() {
      const params = useParams<DocsParams>();
      const { slug } = params; // slug will be an array, e.g., ['getting-started', 'installation']
    
      return (
        <div>
          <h1>Docs Page</h1>
          <p>Path segments: {slug?.join(' / ')}</p>
        </div>
      );
    }
    

    URL Examples:

    • /docs/getting-started -> params.slug is ['getting-started']
    • /docs/getting-started/installation -> params.slug is ['getting-started', 'installation']

    5. Optional Catch-all Segments ([[...slug]])

    Similar to catch-all, but it also matches the base path (where slug would be undefined).

    Route: app/shop/[[...slug]]/page.tsx

    Component:

    // app/shop/[[...slug]]/page.tsx
    'use client';
    import { useParams } from 'next/navigation';
    
    interface ShopParams {
      slug?: string[]; // slug can be undefined or an array
    }
    
    export default function ShopPage() {
      const params = useParams<ShopParams>();
      const { slug } = params;
    
      return (
        <div>
          <h1>Shop Page</h1>
          {slug ? (
            <p>Viewing category: {slug.join(' / ')}</p>
          ) : (
            <p>Viewing all products (base shop page)</p>
          )}
        </div>
      );
    }
    

    URL Examples:

    • /shop -> params.slug is undefined
    • /shop/electronics -> params.slug is ['electronics']
    • /shop/electronics/laptops -> params.slug is ['electronics', 'laptops']

    In summary, useParams is the go-to hook in Next.js App Router for programmatically accessing dynamic URL segments that are defined by your folder structure using [] brackets. It's a fundamental part of building dynamic and data-driven pages in Next.js.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.