Next.js Discord

Discord Forum

Change search params in history state, without causing server component re-render.

Answered
Asian black bear posted this in #help-forum
Open in Discord
Asian black bearOP
I am trying to implement a pattern where certain elements of client side state are appended as search parameters to the URL client side, such that upon navigating back the view can be restored, but without wanting to trigger a server side re-render or fetching of data. To this end I prepared an experimental setup with a client component wrapped in a server component page. In the old times there was an option for shallowRouting or something to make this paradigm work, but it seems to have disappeared in the /app router.

client.tsx
import Client from "./client";

const Server = () => {
  console.log("server rendered");
  return <Client />;
};

export default Server


page.tsx
"use client";

import { Button } from "@mui/material";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useCallback, useRef } from "react";

const TestPage = () => {
  console.log("client rendered");

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

  const numberRef = useRef(1);
  const createQueryPart = useCallback(
    (name: string, value: string) => {
      const params = new URLSearchParams(Array.from(searchParams));
      params.set(name, value);
      const search = params.toString();
      return search ? `?${search}` : "";
    },
    [searchParams]
  );

  return (
    <div className="mx-auto mt-64 max-w-screen-md">
      <div>
        <button
          onClick={() => {
            numberRef.current++;
            router.replace(
              `${pathname}${createQueryPart("digit", `${numberRef.current}`)}`
            );
          }}
        >
          Add Param
        </button>
      </div>
      {JSON.stringify(searchParams)}
    </div>
  );
};
export default TestPage;


Clicking the button causes for server rendered to print to the server console with each parameter increase. Am I missing something?
Answered by Asian black bear
It is a shortcoming of the app dir in Next 13.
View full answer

2 Replies

Asian black bearOP
.The only solution I have found so far is to interact with the history state API directly, although I do wonder if there might be unintended consequences

      const here = new URL(window.location.href);
      here.searchParams.set("meaning", "42");
      history.replaceState(history.state, "", here.toString());
Asian black bearOP
It is a shortcoming of the app dir in Next 13.
Answer