💡
【React】ブラウザ拡張機能が原因のHydration Errorの解消方法
記事概要
ブラウザ拡張機能が原因のHydration Errorについて、整理する。
エラー事象
シークレットモードではエラー発生しないが、標準モードの場合は下記エラーが発生する
A tree hydrated but some attributes of the server rendered HTML didn't match the client properties. This won't be patched up. This can happen if a SSR-ed Client Component used:
- A server/client branch `if (typeof window !== 'undefined')`.
- Variable input such as `Date.now()` or `Math.random()` which changes each time it's called.
- Date formatting in a user's locale which doesn't match the server.
- External changing data without sending a snapshot of it along with the HTML.
- Invalid HTML tag nesting.
It can also happen if the client has a browser extension installed which messes with the HTML before React loaded.
https://react.dev/link/hydration-mismatch
...
// 中略
<html>
<body
className="__variable_188709 __variable_9a8899 antialiased"
- cz-shortcut-listen="true"
>
...
エラー原因
ブラウザ拡張機能がcz-shortcut-listen="true"属性を自動で追加していることにより、サーバー側とクライアント側でレンダリングされるテキストに差が生じるため
- ブラウザの拡張機能を利用していない場合、属性の自動追加は行われない
- ChromeのColorZillaによって、
cz-shortcut-listen="true"属性が追加されている - 拡張機能によって、追加される属性は異なる
エラー解消方法
-
開発環境のみでエラー発生し、本番環境でエラー発生していない場合はコード修正しない
-
body要素に、
suppressHydrationWarning={true}を追加する<body className={`${geistSans.variable} ${geistMono.variable} antialiased`} suppressHydrationWarning={true} //追加 > // 中略 </body>
Discussion