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>.
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.
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.