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 useP
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: C/C++ Code // C
1 min read
Node.js URLSearchParams.get()
In URLSearchParams interface, the get() method returns the first value of the input search parameter. Syntax: URLSearchParams.get(name) Returns:The string will be returned if the name-value pair is found, else null will be returned. Parameters: name - Input the name of the parameter. Example1: When
1 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
Node.js URLSearchParams.getAll()
In URLSearchParams interface, the getAll() method returns all the values of the input search parameter in the form of an array. Syntax: URLSearchParams.getAll(name) Returns: An array of string according to the name-value pairs, else an empty array will be returned. Parameters: name - Input the name
1 min read
Node.js URLSearchParams.set()
In URLSearchParams interface, the set() method sets the value given as an input parameter.If there are several values matching the input parameter then it deletes the others and if the value does not exist then it creates it. Syntax: URLSearchParams.set(name, value) Parameters: name - Input the name
1 min read
Node.js URLSearchParams.append()
In URLSearchParams interface, the append() method adds a key/value pair specified by user. Syntax: URLSearchParams.append(name, value) Parameters: name - Input the parameter name to append value - Input the parameter value to append Example1: let url = new URL('https://example.com?par=1&par1=3')
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.delete()
In URLSearchParams interface, the delete() method deletes the parameter specified by user and all its associated values. Syntax: URLSearchParams.delete(name) Parameters: name - The name of the parameter to be deleted. Example 1: let url = new URL('https://example.com?par=1&bar=2&par=3'); let
1 min read
Node.js URLSearchParams.keys()
In URLSearchParams interface, the keys() method returns an Iterator which allows us to iterate through all the keys present in the object. Syntax: searchParams.keys(); Return:Returns an ES6 Iterator over the names of each name-value pair. Example 1: var searchParams = new URLSearchParams("keyA=
1 min read