One common error you’re likely to encounter in both Next and React apps is the hydration error. Hydration errors result from a mismatch between server- and client-rendered markup and differences in component states.
Specifically, Next.js hydration errors arise when you wrap your components or HTML elements with an improper tag. A common example is when you have a p tag wrapping your divs, sections, or other elements.
The exact error message you’ll get is:
Hydration failed because the initial UI does not match what was rendered on the server
To fix the error, you need to check the markup throughout your application and ensure that you’re not wrapping elements or custom components with improper tags.
For example, the following component will result in a Next.js hydration error because we wrapped the div element inside the paragraph:
import Image from 'next/image'
export const ErrorComponent = ()=>{
return(
<p><div>Don't do this!</div><Image src='/logo.jpg' alt='' width='40' height='40'/></p>
)
}
Rather, use the right “wrapper” elements — e.g. div, section, main, etc. — to wrap your content:
export const CorrectComponent = ()=>{
return(
<div><div>Do this instead</div><Image src='/logo.jpg' alt='' width='40' height='40'/></div>
)
}
Keep in mind that some third-party components, may use the <p> tag as a top-level element. In such cases, you’ll need to wrap the component inside something semantic to avoid the error, like a <div> or <section>.
Properly arranging your HTML will greatly reduce the likelihood of encountering the hydration error in your Next app, but it’s not the only cause. You can also encounter the error after importing and running certain packages, as we will explore in the next section.
don't forget to add a comment.