0
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?

Next.jsのHydration Errorを引き起こしたコード

0
Posted at

問題のコード

  const getInitialValue = () => {
      const params = new URLSearchParams(window.locaton.search);
      const value = params.get('value');
      return value ?? null;
  }
  const [value, setValue] = useState(getInitialValue());

  ...

  return <div>{value}</div>

Hydration Errorの原因

SSR時のHTML

サーバー上ではwindowオブジェクトはnullなので、valuenullになる。

<div></div>

クライアントでの初期レンダリング時のHTML

windowが存在するので、valuenullにならない。

<div>valueの値</div>

こうして二つに差分が起こり、Hydration Errorになる。

どうすればいいのか

クライアントでの初期値もnullにすることで、SSR時のものと同じ結果にする。

  const getInitialValue = () => {
      const params = new URLSearchParams(window.locaton.search);
      const value = params.get('value');
      return value ?? null;
  }
  const [value, setValue] = useState(null);

  useEffect(() => {
      setValue(getInitialValue())
  },[])

  ...

  return <div>{value}</div>
0
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
0
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?