Open In App

Next.js Functions: useSearchParams

Last Updated : 18 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Usesearch_params_folder_strucuter
Folder Structure

Example: 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


Next Article
Article Tags :

Similar Reads