surya
surya

Reputation: 3

Difference between server component and use hook in client component

Difference between the two below snippets of code, request data in server component vs pass promise to client component using use hook

//page.tsx
import { Suspense } from "react";
import Post from "./components/Post";

export default async function Home() {
  return (
    <div>
      <h1>Home</h1>
      <Suspense fallback={<div>Loading...</div>}>
        <Post id={1} />
      </Suspense>
    </div>
  );
}
import React from "react";
import { getPost } from "../lib/getPosts";
import PostCard from "./PostCard";

export default async function Post({ id }: { id: number }) {
  const post = await getPost(id);
  return <PostCard post={post} />;
}

VS

//page.tsx
import { Suspense } from "react";
import { getPost } from "./lib/getPosts";
import PostPromise from "./components/PostPromise";

export default async function Home() {
  const post = getPost(3);
  return (
    <div>
      <h1>Home</h1>
      <Suspense fallback={<div>Loading...</div>}>
        <PostPromise post={post} />
      </Suspense>
    </div>
  );
}
"use client";
import React, { use } from "react";
import { Post } from "../lib/getPosts";
import PostCard from "./PostCard";

export default function PostPromise({ post }: { post: Promise<Post> }) {
  const p = use(post);
  return <PostCard post={p} />;
}

In both cases, I called getPost (to fetch data) only in the server component.

I inspected the network requests, and in both cases, there was no network request for the getPost method, meaning the data fetching happened on the server side. I also checked the page source, which showed the post data. In both cases, the HTML was sent as a stream.

Questions:

Upvotes: -2

Views: 47

Answers (1)

Jairo Py
Jairo Py

Reputation: 968

The main difference is that Server Components render all of your HTML on the server, so when someone visits your page, the post data is already in the delivered HTML. That makes it more SEO-friendly because search engines can see the full content right away.

On the other hand, Client Components fetch data in the browser once the page is loaded, which can delay when crawlers get the actual post content (though modern crawlers can often handle JavaScript).

When to use each approach?

Server Components (SSR): If your content can be pre-rendered and SEO is important. The server handles data fetching and returns ready-to-index HTML.

Client Components: If you need to fetch data based on user interactions or real-time updates. This approach is more flexible for dynamic or highly interactive applications, but you may sacrifice some immediate SEO benefits.

Upvotes: 0

Related Questions