1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

⚡️ServerComponent VS ClientComponent

1
Posted at

:paperclip:一言で言うと】


ServerComponent は、「ページを開いた時、サーバーがHTMLを作って送ってくる」もの。
ClientComponentは、「ブラウザに届いてから、JavaScriptが動いてデータを取ってくるもの」

迷ったらまず、ServerComponent。
ユーザー操作でデータが変わるなら、ClientComponent

:paperclip:それぞれの特徴】


:computer: ServerComponent

  • 初回表示が早い
  • SEO有利
  • JSバンドル小
    :x: 動的更新
// page.tsx (async関数でOK)
const storeName =
  await getStoreNameByCode(storeCode);

return <Component storeName={storeName} />;

:globe_with_meridians: ClientComponent

  • 動的更新⭕️
  • 部分再レンダリング
    :x: 初回ローディングあり
    :x: JSバンドル増加
// "use client" が必要
const { getStoreName } = useStoreNameMap();

return <div>{getStoreName(storeCode)}</div>;

:paperclip:どちらを使うか?判断フロー】


Q1.ユーザーの操作でデータが動的に変わる?

:red_circle:Yes :arrow_forward: ClientComponent(ドロップダウンで店舗切り替えなど)
:white_circle: No(:arrow_down: 次の質問へ)

Q2.ポーリング・WebSocketなどリアルタイム更新が必要か?

:red_circle:Yes :arrow_forward: ClientComponent(定期的な再取得など)
:white_circle: No(:arrow_down: 次の質問へ)

Q3.親コンポーネントがすでにClientComponent?

:red_circle:Yes :arrow_forward: ClientComponent
:white_circle: No :arrow_forward: ServerComponent

:file_folder: PJでのベストプラクティス】


:one:デフォルトは Server Component — 迷ったらまずこちら。初回表示が速く、バンドルサイズも小さい。
:two:親ページでAPIを叩いてpropsで渡す — 子コンポーネントで毎回 use〇〇NameMap() を呼ぶと無駄なAPI呼び出しが増える。
:three:動的更新が必要になって初めて Client Component に変更 — 最初からClientにしない。必要性が出てから切り替える。
:four:必ずエラーハンドリングを入れる — API失敗時に 未登録を返すフォールバックを忘れずに。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?