how to use useParams hook in next.JS ?
Introduction
Next.js 13 has introduced several new features and improvements, including the powerful useParams hook for handling dynamic routes. This article will guide you through the basics of using useParams in your Next.js application, providing your content is both comprehensive and SEO-friendly.
Understanding useParams
The useParams hook is a client-side hook provided by Next.js that allows you to read the dynamic parameters from the current URL. This hook is particularly useful for applications with dynamic routing, such as product pages, user profiles, and more.
Next.js allows you to create dynamic routes by using square brackets in the filenames within the pages directory. For example, to create a dynamic route for a product page, you would create a file named [id].js inside a products folder:
// pages/products/[id].js
import { useParams } from 'next/navigation';
const ProductPage = () => {
const params = useParams();
const { id } = params;
return (
<div>
<h1>Product ID: {id}</h1>
{/* Fetch and display product details using the id */}
</div>
);
};
export default ProductPage;
In this example, the useParams hook is used to access the dynamic id parameter from the URL.
NOTE : The useParams hook is only use in the client component, This will not work in server side rendering in Next.js
Access Parameter in server side rendering (SSR)
you will get searchParams and params, then you can use that default props to access parameters and query parameters:
const Page = async ({ params: { id }, searchParams }) => {
return (
// Your JSX code here
);
}
Conclusion
The useParams hook in Next.js 13 simplifies accessing dynamic URL parameters in client components, while SSR parameters can be accessed via default props. By integrating these tools, you can enhance your application’s dynamic routing capabilities and improve SEO performance.
FAQs
Can the useParams hook be used in server-side rendering (SSR)?
No, the useParams hook is only used in client components. It does not work in server-side rendering. For SSR, you should use the params and searchParams props that are provided to the server-side function.