Published on

Fixing "There was an error while hydrating" in Next.js

Authors
  • Name
    Ripal & Zalak
    Twitter

Fixing "There was an error while hydrating" in Next.js

Introduction

When developing a website with Next.js, you might encounter the following error:

Error: There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.

This error typically occurs due to discrepancies between server-rendered and client-rendered DOM structures. In this guide, we'll explore the causes and solutions for this error.


Common Causes and Fixes

1. Incorrect <head> Usage

Issue:

You may have placed the <head> tag inside a <div>:

return (
  <div>
    <head>
      <title>My Page</title>
    </head>
    <h1>Welcome</h1>
  </div>
)

Solution:

Use Next.js’s <Head> component from next/head instead:

import Head from 'next/head'

return (
  <>
    <Head>
      <title>My Page</title>
    </Head>
    <h1>Welcome</h1>
  </>
)

2. Hydration Mismatch Due to Dynamic Content

Issue:

If you're generating random values during render, hydration mismatches can occur.

Solution:

Move dynamic content into useEffect to ensure consistent server and client renders:

import { useEffect, useState } from 'react'

const RandomNames = () => {
  const [names, setNames] = useState([])

  useEffect(() => {
    setNames(['Ali', 'Elisa', 'Bella', 'Carmen'])
  }, [])

  return (
    <div>
      {names.map((name, index) => (
        <p key={index}>{name}</p>
      ))}
    </div>
  )
}

3. Hydration Issues with External Libraries

Issue:

Some UI libraries (e.g., react-hot-toast, framer-motion) cause hydration errors.

Solution:

Use Next.js's dynamic import to disable server-side rendering:

import dynamic from 'next/dynamic'

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

4. Incorrectly Structured HTML Elements

Issue:

Placing <ul> inside a <p> is invalid HTML:

<p>
  <ul>
    <li>Item 1</li>
  </ul>
</p>

Solution:

Use a <div> instead:

<div>
  <ul>
    <li>Item 1</li>
  </ul>
</div>

5. Missing <body> Structure in _document.js

Issue:

Ensure that elements are correctly structured inside _document.js:

<html lang="en">
  <body>
    <Header />
    {children}
    <Footer />
  </body>
</html>

FAQs

1. How do I identify the exact cause of a hydration error?

Check the console for warnings. Look for invalid HTML structures or content mismatches between server and client.

2. Why does Next.js switch to client rendering?

If the server-rendered HTML doesn't match the client-rendered HTML, Next.js re-renders the page on the client.

3. Can hydration errors impact performance?

Yes. If Next.js falls back to client-side rendering, it can slow down page loads and reduce SEO benefits.

4. Should I always disable SSR for problematic components?

Not always. Try to fix hydration issues first. Disabling SSR should be a last resort.