In Next.js 13, accessing URL parameters within a specific route and utilizing them in a child component might be necessary. However, the process has evolved with the introduction of new hooks and props.

The Solution

Previously, accessing URL parameters was achieved through the useRouter() hook and router.query props. However, in Next.js 13, various hooks and props facilitate accessing URL parameters depending on whether the component is a server or client component.

Types of URL Parameters

There are two main types of URL parameters:

  1. Query Strings

  2. Dynamic Params

Accessing Query Strings

In a server component, the searchParams prop provides access to the query string:

export default function Dashboard(props) {
  const qs = props.searchParams;

  return (
    <main>
      <div>
        <h1>Dashboard</h1>
        <p>Search Params are {qs.myParam}</p>
      </div>
    </main>
  );
}

For client components, the useSearchParams() hook is utilized:

"use client";

import { useSearchParams } from "next/navigation";

export default function Dashboard() {
  const searchParams = useSearchParams();
  const myParam = searchParams.get("myParam");

  return (
    <main>
      <div>
        <h1>Dashboard</h1>
        <p>Search Params are {myParam}</p>
      </div>
    </main>
  );
}

Accessing Dynamic Params

For dynamic route parameters, server components utilize the params prop:

export default function DynamicRouteParam(props) {
  const dynamicParams = props.params;

  return (
    <main>
      <div>
        <h1>Dashboard</h1>
        <p>Params are {dynamicParams.dynamic}</p>
      </div>
    </main>
  );
}

Client components use the useParams() hook:

"use client";

import { useParams } from "next/navigation";

export default function DynamicClientRouteParam() {
  const params = useParams();
  const dynamicParams = params.dynamic;
  
  return (
    <main>
      <div>
        <h1>Dashboard</h1>
        <p>Params are {dynamicParams}</p>
      </div>
    </main>
  );
}

By utilizing these hooks and props, accessing URL parameters in Next.js 13 becomes seamless, whether in server or client components.