MeWrite Docs

Next.js: Hydration failed because the initial UI does not match

Next.js ハイドレーションエラーの解決方法

概要

サーバーサイドレンダリングとクライアントサイドレンダリングの結果が一致しない場合に発生するエラーです。

エラーメッセージ

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

原因

  1. 日時の違い: サーバーとクライアントで異なる時刻
  2. ブラウザAPI使用: windowやdocumentをSSR時に使用
  3. ランダム値: Math.random()やuuidなど
  4. 条件付きレンダリング: サーバーとクライアントで異なる結果

解決策

1. useEffectでクライアント専用コード

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
'use client';
import { useState, useEffect } from 'react';

function CurrentTime() {
  const [time, setTime] = useState('');

  useEffect(() => {
    setTime(new Date().toLocaleString());
  }, []);

  return <span>{time}</span>;
}

2. dynamic importでSSR無効

1
2
3
4
5
6
import dynamic from 'next/dynamic';

const ClientOnlyComponent = dynamic(
  () => import('./ClientOnlyComponent'),
  { ssr: false }
);

3. suppressHydrationWarning

1
2
3
<time dateTime={date} suppressHydrationWarning>
  {date}
</time>

4. mounted状態チェック

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function MyComponent() {
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  if (!mounted) return null;

  return <div>{window.innerWidth}</div>;
}

よくある間違い

  • typeof window !== ‘undefined’ でも初期レンダリングは同じにする必要
  • ブラウザ拡張機能がDOMを変更

Next.js の他のエラー

最終更新: 2025-12-09