Next.js Functions: useSearchParams
Last Updated :
18 Sep, 2024
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.
Syntax:
'use client'
import { useSearchParams } from 'next/navigation'
export default function SearchBar() {
const searchParams = useSearchParams()
const search = searchParams.get('search')
// URL -> `/dashboard?search=my-project`
// `search` -> 'my-project'
return <>Search: { search } </>
}
- Query Parameters: Key/value pairs appended to the URL as a way to pass information back and forth from a server.
- useSearchParams: A hook introduced in React 16.8 that lets you use state and other React features in functional components.
Parameters: The useSearchParams hook does not take any parameters. It's called without arguments and returns an object representing the query parameters in the URL.
Returns:
The useSearchParams hook returns a ReadonlyURLSearchParams object, which provides methods to read the query parameters from the URL. Some useful methods include:
- get(parameter: string): string | null: Returns the value of the specified query parameter, or null if it doesn’t exist.
- entries(): Returns an iterator for all query parameters.
Example: The get() method fetches the query parameter from the URL (e.g., ?query=nextjs).
JavaScript
//src/app/search/page.tsx
import { useSearchParams } from "next/navigation";
export default function SearchPage() {
const searchParams = useSearchParams();
const query = searchParams.get("query");
// Get 'query' parameter
return (
<div>
<h1>Search Results</h1>
<p>Query: {query || "No query provided"}</p>
</div>
);
}
Static Generation (SSG)
Static Rendering (i.e., using Next.js’s getStaticProps) does not work with useSearchParams, as static pages are generated at build time. Since query parameters are only available when a user requests a page, this feature doesn’t work in statically rendered components.
Dynamic Rendering
Dynamic rendering occurs when query parameters change after the page loads, and you want to fetch or update data based on the URL. Below is an example where we dynamically update the URL and display the updated query parameter on the page.
Example: Clicking the button updates the URL with a new query string, changing it to ?query=updated. The new query value is then displayed.
JavaScript
//src/app/dynamic-rendering/page.tsx
import { useSearchParams } from "next/navigation";
import { useRouter } from "next/router";
export default function DynamicRenderingPage() {
const router = useRouter();
const searchParams = useSearchParams();
const updateQuery = () => {
router.push("/search?query=updated");
};
return (
<div>
<p>Current Query: {searchParams.get("query")}</p>{" "}
{/* Show the current query parameter */}
<button onClick={updateQuery}>Update Query</button>{" "}
{/* Button to change the query */}
</div>
);
}
Server Components
The useSearchParams hook does not work in server components. It’s meant to be used in client-side components since the server cannot access the URL’s query parameters. If you need query parameters in server components, you’ll have to use getServerSideProps instead.
Pages
In Next.js, the folder structure determines the URL routing. For example, if you place your page.tsx file in the src/app/search directory, it will automatically map to the /search URL. There’s no need to configure routing manually.
JavaScript
//src/app/search/page.tsx
import { useSearchParams } from "next/navigation";
export default function SearchPage() {
const searchParams = useSearchParams();
const query = searchParams.get("query");
return (
<div>
<h1>Search Page</h1>
<p>Query: {query || "No query provided"}</p>
</div>
);
}
Layouts
Next.js uses layouts to wrap multiple pages with a common structure (such as a navigation bar or footer).
Example: The children prop represents any page wrapped by the layout. The layout can be used for multiple pages, ensuring a consistent structure.
JavaScript
//src/app/layout.tsx
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<header>My App Header</header>
<main>{children}</main>
</body>
</html>
);
}
Version History
- Next.js 12: Basic handling of URLs with query strings.
- Next.js 13 (App Router): Introduced the useSearchParams hook to handle query parameters easily in client-side rendering.
Steps To Use useSearchParams function
Step 1: Create a New Next.js Application
npx create-next-app@latest use-searchparams-demo
Step 2: Navigate to the Project Folder
cd use-searchparams-demo
Step 3: Install Required Modules
Next.js includes everything you need, so no extra installations are required. Just ensure you are using an updated Next.js version:
npm install next@latest
Dependencies:
"dependencies": {
"next": "^14.2.12",
"react": "^18",
"react-dom": "^18"
}
Folder structure
Folder StructureExample: Here’s the Example code for the search page using useSearchParams:
JavaScript
// src/app/page.tsx
"use client"
import { useSearchParams } from 'next/navigation';
import SearchPage from "../app/search/page";
export default function Home() {
const searchParams = useSearchParams();
const query = searchParams.get('query');
return (
<div>
<h1>Home Page</h1>
<p>Search Query: {query || 'No query provided'}</p>
<SearchPage />
</div>
);
}
JavaScript
// src/app/search/page.tsx
"use client";
import { useSearchParams } from 'next/navigation';
export default function SearchPage() {
const searchParams = useSearchParams();
const query = searchParams.get('query');
return (
<div>
<h1>Search Page</h1>
<p>Query: {query || 'No query provided'}</p>
</div>
);
}
JavaScript
//src/app/dynamic-rendering/page.tsx
"use client";
import { useSearchParams, useRouter } from 'next/navigation'; // Correct imports
export default function DynamicRenderingPage() {
const router = useRouter();
const searchParams = useSearchParams();
const updateQuery = () => {
router.push('/dynamic-rendering?query=updated');
};
return (
<div>
<h1>Dynamic Rendering Example</h1>
<p>Current Query: {searchParams.get('query')}</p> {/* Show current query parameter */}
<button onClick={updateQuery}> Update Query </button> {/* Button to update query */}
</div>
);
}
Start the project By using the below command
npm run dev
Output
Similar Reads
Next.js Functions: useParams
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 usePa
4 min read
Node.js URLSearchParams.entries()
In the URLSearchParams interface, the entries() method returns an iterator that allows iterating through all the key/value pairs present in the object. The key/value is USVString objects. Syntax: searchParams.entries(); Return: Iterator, iterating over all key-value pairs. Example 1: javascript /
1 min read
Node.js URLsearchParams API
Node.js is an open-source project widely used for the development of dynamic web applications. The URLSearchParams API in Node.js allows read and write operations on the URL query. The URLSearchParams class is a global object and used with one of the four following constructors. Constructors: new UR
4 min read
Node.js URLSearchParams.forEach()
In URLSearchParams interface, the foreach() method returns an iterator which allows to iterate through all values contained in this object with the help of a callback function. Syntax: searchParams.forEach(callback); Return: It does not return anything, used for invoking the function and iterating t
1 min read
Underscore.js _.rest() Function
The Underscore.js is a JavaScript library that provides a lot of useful functions like the map, filter, invoke etc even without using any built-in objects. The _.rest() is used to return the rest of the elements except the zeroth indexed element. Second parameter is used to start the search from the
3 min read
Node.js URLSearchParams.sort()
In the URLSearchParams interface, the sort() method helps to sort all keys/pairs in place. The sort criteria are unicode points of the keys. This method uses a stable sorting algorithm. Syntax: searchParams.sort(); Return: Sorted order of existing name-value pairs in place by their names. Example
1 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
Next.js Functions: generateStaticParams
"generateStaticParams" is a function name or identifier used as a placeholder in the context of NextJS development. It doesn't represent a built-in or standard function in NextJS itself. Instead, it seems to be a hypothetical function name that could be used to illustrate the process of generating s
10 min read
Node.js urlSearchParams.get() Method
The urlSearchParams.get() method is an inbuilt application programming interface of class URLSearchParams within url module which is used to get the value for particular name entry present in the URL search params object. Syntax: const urlSearchParams.get( name ) Parameter: This method takes the nam
2 min read
Underscore.js _.lastindexOf() Function
_.lastIndexOf() function: It finds the index of an element in an array. If the element is repeated then it gives the index of that element which is closest to the end. It is used when we have a number of repeated elements in the array and we want to find the index of that repeated element which is n
3 min read