Search code examples
reactjsnext.js

Next js set query param. Why this way?


next docs and other answers in google recomends change query params like this

  const searchParams = useSearchParams();
  const pathname = usePathname();
  const router = useRouter();

  function handleFilter(title, value) {
    const params = new URLSearchParams(searchParams.toString());
    params.set(title, value);
    router.replace(`${pathname}?${params}`, { scroll: false });
  
  }

But this way it works too:

  const router = useRouter();
  const pathname = usePathname();

  function handleFilter(title, value) {
   router.replace(`${pathname}?${title}=${value}`, { scroll: false });
  }

why is it recommended everywhere to use this complex method and not just router.replace()?

Both methods are working and i don't see any difference


Solution

  • Basically in the first method, you are first preserving the state and then updating only specific(title) values. In the second method, you are just setting the new query string without preserving the state.