#update query params on client side components

1 messages · Page 1 of 1 (latest)

green wave
#

How can I update a query param when something change in my client side component?

cyan ermineBOT
#

Hi @green wave. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To update query parameters in a client-side component in Next.js, you can use the useRouter hook from next/navigation. Here's how you can do it:

  1. Import the useRouter hook in your client component:
'use client'

import { useRouter } from 'next/navigation'
  1. Use the useRouter hook to get access to the router object:
const router = useRouter()
  1. When you want to update the query parameters, you can use the router.push or router.replace method. Here's an example of how to update a query parameter:
const updateQueryParam = (name: string, value: string) => {
  const params = new URLSearchParams(searchParams.toString())
  params.set(name, value)
  router.push(`${pathname}?${params.toString()}`)
}

This code snippet is adapted from the example provided in the Next.js documentation for useSearchParams (https://nextjs.org/docs/app/api-reference/functions/use-search-params#examples).

Keep in mind that updating query parameters will cause a re-render of your component and potentially trigger a new server request if you're using server components that depend on these parameters.

If you want to avoid a full page reload and only update the URL, you can use the { scroll: false } option:

router.push(`${pathname}?${params.toString()}`, { scroll: false })

Remember that when using client-side navigation to update query parameters, you should handle both the initial server-side render (using the searchParams prop in your page component) and subsequent client-side updates (using the useSearchParams hook in your client components).