Next.js - useSearchParams() Function



The useSearchParams() Function

The Next.js useSearchParams() function is used to access current URL's query string. This function is only available in the client-side.

Syntax

The syntax for the useSearchParams() function is as follows:

'use client'

import { useSearchParams } from 'next/navigation'

const searchParams = useSearchParams()

const search = searchParams.get('search')

Parameters

The useSearchParams() function does not accept any parameters.

Return Value

The useSearchParams() function returns an object called searchParams. This object has a get() method that returns the value of the specified parameter. If the parameter is not found, the method returns null. For example,

URL searchParams.get("a")
/dashboard?a=1 '1'
/dashboard?b=3 null
/dashboard?a=1&b=2 '1'

You can use getAll() function on searchParams object to get all the parameters values.

Example 1

In the example below, we are using the useSearchParams() function to access the current URL's query string and display it in the console.

'use client'
 
import { useSearchParams } from 'next/navigation'
 
export default function ExampleClientComponent() {
  const searchParams = useSearchParams()
 
  console.log(searchParams.get('a'))
 
  return (<h2>Next.js Search Params</h2>)
}

Output

Next.js useSearchParams Function Example 1

Example 2

In the example below, we are using the useSearchParams() function to access the current URL's query string and display it in the current page itself.

'use client'
 
import { useSearchParams } from 'next/navigation'
 
export default function ExampleClientComponent() {
  const searchParams = useSearchParams()
 
  return (
    <div>
        <h1>Current URL query string: {searchParams.get('q')}</h1>
    </div>
  )
}

Output

Next.js useSearchParams Function Example 2
Advertisements