Originally published at https://www.wisdomgeek.com on March 13, 2024.
Within a React or Next.js app, if you encounter the error “Hydration failed because the initial UI does not match what was rendered on the server”, there could be a few reasons for it.
Let us look at all the possible reasons and potential fixes for the error.
Potential issues
Incorrect HTML formatting
The most common cause for the error is incorrect HTML formatting in our code.
But why does the browser not tell you that but instead throws the error “Hydration failed because the initial UI does not match what was rendered on the server”? Because the browser tries to fix these on its own and then does a comparison of the HTML it has from what the server sent, it fails to match the two. Thus it throws the generic error.
Some examples of invalid HTML are as follows.
Having a div element inside a paragraph is not allowed.
export const IncorrectComponent = () => {
return (
<p>
<div>Incorrect HTML</div>
</p>
)
}
A paragraph inside another paragraph is erroneous too. The same goes for an H1, or a list item too.
export const IncorrectComponent = () => {
return (
<p>
<p>p inside paragraph is invalid</p>
<h1>H1 inside paragraph is invalid too</h1>
</p>
)
}
export const AnotherIncorrectComponent = () => {
return (
<ul>
<p>
<li>Incorrect HTML</li>
</p>
</ul>
)
}
The Link tag that is provided by Next.js is already rendered as an anchor component. Trying to add another anchor inside it will throw an error too, since an anchor cannot be placed inside another.
export const IncorrectComponent = () => {
return (
<Link>
<a>Link tag already creates an anchor tag, so this errors too</a>
</Link>
)
}
A