Next.js app router avoids repeated serialization embeds when passing from server to client components
Matthew Wang
Posted on September 17, 2024
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>
);
}
This data is embedded in the html that is fetched.
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).
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>
);
}
This is great to know if you are optimizing for performance on large data sets.
💖 💪 🙅 🚩
Matthew Wang
Posted on September 17, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.