How to Add/Update Query Params in a Next.js Client Component?

In a Next.js client component, you can add or update URL query params in the following steps:

  1. Accessing the router object using the useRouter() hook;
  2. Handling the add/update of query params in the useEffect() hook by:
    1. Creating a new JavaScript URL object from the current window URL;
    2. Setting the query params you wish to add using the URLSearchParams.set() method;
    3. Adding the new URL to the router object.

For example, you can implement these steps in the following client component:

// MyComponent.jsx
import React, {useEffect, useState} from 'react';
import { useRouter } from 'next/router';

export const MyComponent = () => {
  const [currPage, setCurrPage] = useState(1);
  // 1: access the `router` object
  const router = useRouter();

  // 2: handle modifying query params in `useEffect`
  useEffect(() => {
    // 2.1: create `URL` from `window` URL
    const url = new URL(window.location.href);
    // 2.2: add query params you wish to add
    url.searchParams.set('page', currPage.toString());
    // 2.3: add the new URL to the `router` object
    router.push(url.toString());
  }, [currPage]);

  const gotoNextPage = () => {
    setCurrPage((prevCurrPage) => parseInt(prevCurrPage, 10) + 1);
  };

  return (
    <button onClick={gotoNextPage}>Next</button>
  );
}

In this example, everytime the "currPage" value changes, it will run the effect, and add/update the query parameter to reflect the currPage value.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.