How to use Nextjs useParams Hook

Introduction

Next.js 13 has introduced several new features, including the powerful useParams hook for handling dynamic routes. This guide will walk you through the basics of using nextjs useParams hook in your application, making your content both comprehensive and SEO-friendly.

Understanding Nextjs useParams Hook

The useParams hook is a client-side hook in Next.js that lets you read dynamic parameters from the current URL. This is particularly useful for dynamic routing in applications, such as blog pages or user profiles.

useParams returns an object containing the current route’s filled in dynamic parameters.

  • Each property in the object is an active dynamic segment.
  • The properties name is the segment’s name, and the properties value is what the segment is filled in with.
  • The properties value will either be a string or array of string‘s depending on the type of dynamic segment.
  • If the route contains no dynamic parameters, useParams returns an empty object.
  • If used in Pages Router, useParams will return null on the initial render and updates with properties following the rules above once the router is ready.

To create a dynamic route in Next.js, you use square brackets in filenames within the pages directory. For example, to create a dynamic route for a blog details page, you would create a file named [id].js inside a products folder:

// pages/blogs/[id].js
import { useParams } from 'next/navigation';

const BlogDetails = () => {
  const params = useParams();
  const { id } = params;

  return (
    <div>
      <h1>Blog ID: {id}</h1>
      {/* Fetch and display blog details using the id */}
    </div>
  );
};

export default BlogDetails;

In this example, the useParams hook is used to access the dynamic id parameter from the URL.

Note: The Nextjs useParams hook is only used in client components. It will not work with server-side rendering (SSR) in Next.js.

Accessing Parameters in SSR

To access parameters in server-side rendering, you will use params and searchParams provided by default props:

const Page = async ({ params: { id }, searchParams }) => {
  return (
    // Your JSX code written here
  );
};

Advanced Example with Data Fetching & using Nextjs useParams

To further illustrate the use of Nextjs useParams, let’s extend the example to fetch product data based on the dynamic id parameter:

// pages/blogs/[id].js
import { useParams } from 'next/navigation';
import { useEffect, useState } from 'react';

const BlogDetails = () => {
  const params = useParams();
  const { id } = params;
  const [blogDetails, setBlogDetails] = useState(null);

  useEffect(() => {
    const fetchProduct = async () => {
      const response = await fetch(`/api/blogs/${id}`);
      const data = await response.json();
      setProduct(data);
    };

    fetchProduct();
  }, [id]);

  if (!blogDetails) return <div>Loading...</div>;

  return (
    <div>
      <h1>{blogDetails.name}</h1>
      <p>{blogDetails.description}</p>
      <p>Price: ${blogDetails.price}</p>
    </div>
  );
};

export default BlogDetails;

In this case, getServerSideProps fetches the blog details page data before rendering the page, ensuring the content is ready when the user visits the page.

SEO Best Practices

To optimize your Next.js application for search engines, follow these best practices:

  1. Meta Tags: Ensure your pages have descriptive meta titles and descriptions that include relevant keywords.
  2. Optimized Images: Use Next.js’s Image component to serve optimized images for better performance.
  3. Sitemap: Include all your dynamic routes in your sitemap to help search engines index your content.
  4. Performance: Utilize Next.js features like lazy loading, code splitting, and server-side rendering to improve load times.

Conclusion

The Nextjs useParams hook 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 Nextjs useParams hook be used in server-side rendering (SSR)? No, the useParams hook is only used in client components. For SSR, use the params and searchParams props provided to the server-side function.

By implementing the useParams hook correctly and following SEO best practices, you can significantly enhance the functionality and visibility of your Next.js applications.

For more detailed information, visit the original article: How to Use useParams Hook in Next.js.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top