I used to think that when you declare a page or component with the "use client"
directive, you won't be able to see those pages on the "View Page Source" of browsers, since they are rendered only on the client side, using JS (Just like what happens for pure React).
However, I just tested this case and realized almost all of the content written under "use client" still shows on the page source. So what is the difference between Server Components and Components with "use client" directive regarding SEO?
Does using Server Components help SEO as well? Or its main application is for improving performance?
Indeed with Next.js in the app
directory, both Server and Client components render first on the server, and get sent as HTML to the browser (you can see the generated HTML files per page inside .next/sever/app
after building your project).
The difference between the two is that when you add "use client", it means this component includes client interactivities, so Next.js should send the additional JavaScript needed (such as event handlers, effects, etc) and attach it to the HTML while transforming it to React elements.
Now, regarding SEO, there is no difference for static components where there is no data fetching involved. For example, the below component would have similar performance regarding SEO whether you add "use client"
or not:
export default function Component() {
return <div>Lorem, ipsum dolor sit amet consectetur adipisicing elit.</div>;
}
But say you have to fetch some data across the internet. Well, the below server component is sent with its fetched data to the browser as part of the initial HTML, while the following client one is sent as an empty div
:
export default async function Component() {
const res = await fetch("API_URL");
const data = await res.json();
return (
<div>
{data.map((item) => (
<div key={item.id}>{item.content}</div>
))}
</div>
);
}
"use client";
import { useEffect, useState } from "react";
export default function Component() {
const [data, setData] = useState([]);
useEffect(() => {
async function fetcher() {
const res = await fetch("API_URL");
const data = await res.json();
setData(data);
}
}, []);
return (
<div>
{data.map((item) => (
<div key={item.id}>{item.content}</div>
))}
</div>
);
}