🌊

Next.jsでライブラリ使用中にHydration Errorエラーが起きる時の対処法

に公開

追記

2025年9月23日(火)

該当のPRがマージされており、
react-selectを使用するコンポーネントをuse clientつけたら無事使えました。(next:15.5.0)

これを見る感じだとSSRはサポートされている様子。
https://react-select.com/advanced

SSR / Universal Rendering
React-Select uses Emotion for CSS which has zero-config server rendering. This means that all you need to do to server-render React-Select is call React's renderToString or use a framework like Next.js or Gatsby and it will work.

import { renderToString } from 'react-dom/server'
import App from './App'

const html = renderToString(<App />)

記事本文

Next.jsで開発しているとよく起こる Hydration Error

https://nextjs.org/docs/messages/react-hydration-error#solution-2-disabling-ssr-on-specific-components

そもそも通常のReactのライブラリはSSRを想定して作られていないので、
対応していないとハイドレーションエラーになることがあります。

今回は、Next.js環境下で、react-selectを使用時に、謎のエラーが発生しました。
PRは作成されているのですが、マージがされていない。。
https://github.com/JedWatson/react-select/issues/5859

selectboxはクライアントサイドだけで描画されてくれればいいので、
とりあえず以下のように dynamic import で対応。
非同期のimportと描画が終わるまで、一瞬領域が空になってしまうので、
loadingにフォールバックの要素を設定してあげましょう。

selectbox.jsx
'use client'

import dynamic from 'next/dynamic'

const Select = dynamic(() => import('react-select'), {
  ssr: false,
  loading: () => <div className='flex h-full items-center'>...loading</div>,
})

export function SelectBox({ options, instanceId, ...props }) {
  return (
    <div className='h-[40px]'>
      <Select
        {...props}
        options={options}
        name={instanceId}
        instanceId={instanceId}
      />
    </div>
  )
}

https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading#adding-a-custom-loading-component

Discussion