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?

More than 1 year has passed since last update.

【Next.js】SSRを回避する方法

Posted at

Next.jsにおいてSSRを回避し、useLayoutEffectなどを正常に使用する方法について記載します。

dynamicを使用する

dynamic{ssr: false}を指定することでSSRを回避できます。

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

Suspenseを使用する

以下のように記述するとクライアント側で


<Suspense fallback={<Loading />}>
  <Sample />
</Suspense>

function Sample() {
  if (typeof window === 'undefined') {
    throw Error('Sample should only render on the client.');
  }
  // ...
}

SSRではエラーとなり、最も近いSuspensefallbackに指定したLoadingが表示されます。
クライアントで正常に処理が完了するとSampleが表示されます。

isMounted stateを使用する

以下のように記述するとコンポーネントがハイドレーションの後にのみレンダリングされます。

export function Sample() {
  const [isMounted, setIsMounted] = useState(false)

  useEffect(() => {
    setIsMounted(true)
  }, [])

  return isMounted ? <RealContent /> : <FallbackContent />
}

useEffectはクライアントでのみ実行されるため、SSRではFallbackContentがレンダリングされ、useEffectが実行されるとRealContentが表示されます。

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?