Next.js Functions: useParams
Last Updated :
31 Jul, 2024
Next.js is known for its ability to create dynamic and highly optimized web applications. Among them, useParams allows you to access route parameters and enhance the interactivity and functionality of the applications. In this article, we will explore what useParams is and how it works.
What is useParams?
In Next.js, useParams is a hook used to retrieve the parameters from the URL of a dynamic route. Dynamic routing is a key feature in Next.js that enables developers to create pages with variable paths. These variable paths can capture segments of the URL as parameters, which can then be used to fetch data or render specific content.
For example, a blog application might have a route for individual posts like /posts/[id]
, where [id]
is a dynamic segment representing the post ID.
How to Use useParams?
To use useParams, you need to create a dynamic route and then access the parameters within a page or component.
Steps to Implement useParams
Step 1: Run the following command to create a new Next Application.
npx create-next-app myproject
When we open our app in a code editor we see the following project structure.
Project Structure
Folder Structure
Dependencies
"dependencies": {
"react": "^18",
"react-dom": "^18",
"next": "14.2.5"
}
Approach:
The useParams hook allows you to read dynamic parameters from the current URL in a Next.js application, making it particularly useful for creating dynamic routes such as product pages or user profiles.
Next.js utilizes a file-based routing system, enabling the creation of dynamic routes by using square brackets in filenames within the app directory.
For example, to configure a dynamic route for a product page, you would create a folder named [id] inside the app/products directory, and place a page.tsx (or page.js if not using TypeScript) file inside this folder. This setup enables the page to respond to different product IDs dynamically based on the URL.
Example: In this example a profuct page is created clicking on each product a new product details page opens up.
JavaScript
// src/app/products/product.tsx
import Link from "next/link";
type Product = {
id: string,
name: string,
description: string,
price: number,
};
const products: Product[] = [
{
id: "1",
name: "Product 1",
description: "Description for Product 1",
price: 100,
},
{
id: "2",
name: "Product 2",
description: "Description for Product 2",
price: 200,
},
];
const ProductList: React.FC = () => {
return (
<div>
<h1>Product List</h1>
<ul>
{products.map((product) => (
<li key={product.id}>
<Link href={`/products/${product.id}`}>{product.name}</Link>
</li>
))}
</ul>
</div>
);
};
export default ProductList;
JavaScript
// src/app/products/[id]/page.tsx
"use client";
import { useParams } from "next/navigation";
import { useEffect, useState } from "react";
type Product = {
id: string,
name: string,
description: string,
price: number,
};
const ProductPage: React.FC = () => {
const params = useParams();
const { id } = params;
const [product, setProduct] = (useState < Product) | (null > null);
useEffect(() => {
if (id) {
const products: Product[] = [
{
id: "1",
name: "Product 1",
description: "Description for Product 1",
price: 100,
},
{
id: "2",
name: "Product 2",
description: "Description for Product 2",
price: 200,
},
];
const foundProduct = products.find((prod) => prod.id === id);
setProduct(foundProduct ?? null);
}
}, [id]);
if (!product) {
return <div>Loading...</div>;
}
return (
<div>
<h1>Product ID: {id}</h1>
<h2>{product.name}</h2>
<p>{product.description}</p>
<p>Price: ${product.price}</p>
</div>
);
};
export default ProductPage;
Step to run the application: Run your Next.js app using the following command:
npm run dev
Output:
Benefits of Using useParams
Dynamic Content Rendering: The primary benefit of using useParams is the ability to render dynamic content based on URL parameters. This is essential for applications like blogs, e-commerce sites, and user profiles, where the content changes based on the URL segment.
Improved User Experience: Dynamic routing enhances the user experience by providing more interactive and personalized content. Users can navigate directly to specific items or pages without needing to go through a static list.
SEO Optimization: Next.js supports server-side rendering (SSR) and static site generation (SSG), both of which can use dynamic routes for improved SEO.
Simplified Codebase: Using dynamic routes and useParams helps keep your codebase clean and manageable. Instead of creating multiple static pages, you can create a single dynamic template that handles various URL segments.
Similar Reads
Next.js Functions: useSearchParams
The Next.js useSearchParams hook gives the functional component access to the query parameters from the URL and the ability to manipulate them. This is pretty useful in cases where you need to get, parse, or change search parameters directly within the component, without manually parsing the URL.Syn
5 min read
Node.js sort() function
sort() is an array function from Node.js that is used to sort a given array. Syntax: array_name.sort() Parameter: This function does not take any parameter. Return type: The function returns the sorted array. The program below demonstrates the working of the function: Program 1: javascript function
1 min read
Node.js push() function
push() is an array function from Node.js that is used to add elements to the end of an array. Syntax:array_name.push(element)Parameter: This function takes a parameter that has to be added to the array. It can take multiple elements also. Return type: The function returns the array after adding the
1 min read
Less.js Misc Functions
Less.js is a CSS preprocessor which basically means that it provides some additional features to the traditional CSS which helps us to write CSS code more efficiently. All the Misc functions are explained below. In this article, we are going to learn about the Misc or Miscellaneous functions that ar
4 min read
Underscore.js _.result() Function
Underscore.js is a JavaScript library that provides a lot of useful functions that helps in the programming in a big way like the map, filter, invoke etc even without using any built-in objects. The _.result() function is an inbuilt function in Underscore.js library of JavaScript. Here, if the state
2 min read
JavaScript Function Parameters
Function parameters are variables defined in the function declaration that receive values (arguments) when the function is called. They play a key role in making functions reusable and dynamic.Values are assigned to parameters in the order they are passed.You can assign default values to parameters
2 min read
p5.js getURLParams() Function
The getURLParams() function is used to return the current URL parameters a JavaScript object, with each parameter as a separate member of the object. Syntax: getURLParams() Parameters: This function does not accept any parameters. Return Value: It returns an Object of the path parameters. Below exam
1 min read
Less.js String Functions
Less.js (Leaner Style Sheets) is an extension to normal CSS which basically enhances the abilities of the normal CSS and gives it programmable powers like variables, functions, loops, etc. String functions are one such type of function provided by Less.js to perform operations on a string like repla
6 min read
Underscore.js _.wrap() Function
Underscore.js _.wrap() is used to wrap a function inside another function. It means that the first calling function will be invoked first and then the called function will be executed. If the calling function does not call the called function then the second function will not be executed. Syntax:_.w
3 min read
Less.js List Functions
Less.js (Leaner Style Sheets) is an extension to normal CSS which basically enhances the abilities of the normal CSS code and gives it more functionalities and programmable features. Less.js provides us with many List Functions which are basically functions that we can perform on a list of elements
7 min read