DEV Community

Matthew Wang
Matthew Wang

Posted on

Next.js app router avoids repeated serialization embeds when passing from server to client components

You may know that passing data from server to client component means that Next.js needs to serialize the data before passing it to the client.

import ClientComp from "./ClientComp";

// Server component
export default function TestPage() {
  const data = { rabbit: "Rabbit", hole: "Hole" };
  return (
    <div>
      <ClientComp data={data} />
      <ClientComp data={data} />
      <ClientComp data={data} />
      <ClientComp data={data} />
      <ClientComp data={{ copy321: "copy321", copy123: "copy123" }} />
      <ClientComp data={{ copy321: "copy321", copy123: "copy123" }} />
      <ClientComp data={{ copy321: "copy321", copy123: "copy123" }} />
      <ClientComp data={{ copy321: "copy321", copy123: "copy123" }} />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

This data is embedded in the html that is fetched.

dev tools showing embedded data

Does that mean that duplicate data will be embedded repeatedly?

Actually no! (if you use the same reference)

Next.js ensures that the same reference is not embedded multiple times.

The data will be embedded repeatedly only if you create a non-equal object (new reference).

dev tools show duplicate

Note: using the same reference works even for nested server components.

export default function TestPage() {
  const data = { rabbit: "Rabbit", hole: "Hole" };
  return (
    <div>
      <ClientComp data={data} />
      <ClientComp data={data} />
      <ClientComp data={data} />
      <ClientComp data={data} />
      <Nest data={data} />
    </div>
  );
}

function Nest(props: { data: Record<string, string> }) {
  return (
    <div>
      <ClientComp data={props.data} />
      <ClientComp data={props.data} />
      <ClientComp data={props.data} />
      <ClientComp data={props.data} />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

This is great to know if you are optimizing for performance on large data sets.

Top comments (0)