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?

React初心者がHydration Errorで初めて"use client"の意味を理解した話

1
Posted at

はじめに

Next.jsでMUIを使って画面を作っていたときに、Hydration Errorが発生しました。

最初はエラー内容を見ても全く意味が分からず、「use client」を付けると直るという記事を見つけましたが、「なぜ直るのか」が理解できませんでした。

今回は、自分なりに調べて理解した内容を初心者向けにまとめます。

発生したエラー

コンポーネントを表示すると、次のようなHydration Errorが表示されました。

Hydration failed because the initial UI does not match what was rendered on the server.

原因

Next.jsでは、デフォルトでServer Componentとして動作します。

Server Componentでは、

  • useState
  • useEffect
  • イベント(onClickなど)

を使用できません。

一方、MUIのButtonやTextFieldなどは内部でクライアント側の機能を利用しているため、Server Componentのままだとエラーになる場合があります。

実際の修正

"use client";

import Button from "@mui/material/Button";

export default function Sample() {
  return <Button>送信</Button>;
}

学んだこと

最初は「use clientを書けば直る」とだけ覚えていました。

しかし調べてみると、

  • Server Component
  • Client Component
  • Hydration

というNext.jsの仕組みを理解することが重要だと分かりました。

今後は「とりあえず付ける」のではなく、「なぜ必要なのか」を意識して実装したいと思います。

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?