Warning Expected server HTML to contain a matching in Next.js

Hydration Error in Next.js

You might get the following Error

Unhandled Runtime Error
Error: Hydration failed because the initial UI does not match what was rendered on the server.

Warning: Expected server HTML to contain a matching <li> in <a>.

See more info here: https://nextjs.org/docs/messages/react-hydration-error

There are several reasons for why these errors can occur.

Solution 1

Why this occurs?

You get this error as Next.js runs the code on the Server side as well as Client side but sometimes certain code can't be run on the server. For that you need to go for this solution. Since useEffect only runs on the client side during react hydration which indicates that browser api's are available once useEffect runs. This means window is available as well which means we have a browser 🌍.

You can create this hook 'useHasMounted' and only render the component when mounted. This means it won't run on the server.

  import React from 'react';
  import useHasMounted from './useHasMounted'

  export default function App() {
    const hasMounted = useHasMounted()
    console.log({ hasMounted })
    return (
      <h1>I'm a Sandbox!</h1>
      {hasMounted && <p>I am a mounted client component</p>}

Declare it in the component impacted.

Why does this happen?

This happens because the code can't be executed on the Server so it gives you a mismatched HTML.

Solution 2

Check the HTML markup. Sometimes we can add a div inside a link or add invalid HTML. This incorrect nesting can lead to this error.

Last updated:

. . .

Frontend Snacks ðŸŋ

💌 A Frontend Newsletter you'll love, Get FREE weekly Snacks

  • ðŸŽĻ A code snippet to teach Complex Topics visually
  • 🚀 Latest Frontend Gossip
  • 👉 Frontend Developer Toolkit - with FREE templates and tools

ðŸŠī All this to help you grow as a developer & in your day to day!

No spam, unsubscribe anytime.