React 18 Hydration Issue with Nextjs

Written on 2023-03-08 by Adam Drake - 3 min read

Image of React 18 Hydration Issue with Nextjs

I recently was creating a new Nextjs application and I ran into a problem whereif I refreshed the page manually on the keyboard Nextjs would start screaming atme and my console was full of error messages. Like the below:

For me the error message was a little cryptic:

Warning: Expected server HTML to contain a matching <button> in <button>.
It tells you that this sort of error occurs when some code on your page is relying on something that could differ between pre-rendering and the browser.

It turns out it was a React Hydration Error. After a bit of googling I stumbled upon this page: https://nextjs.org/docs/messages/react-hydration-error. It tells you that this sort of error occurs when some code on your page is relying on something that could differ between pre-rendering and the browser. This is connected with server-side-rendering (SSR) and if you don’t take the time to sit down and understand it properly it will no doubt catch you out at some point (like it just did for me!!).

There is this article from Josh Comeau who does a great job of explaining why this error occurs and what you can do to resolve it. There is also the same solution found in this Github Issue on the Nextjs Github Repo.

Code changes

This was my code before:

Code block for Nextjs hydration issue


This was my code after:

Code Block of Nextjs Code Hydration issue


Now the error has gone away!

Conclusion

I have to say that Josh Comeau’s analogy with the cereal box in his article really helped illustrate the point for me. Cereal boxes can be printed way in advance (static non personal content) and then when the cereal is actually put in the box the ‘sell by date’ can be printed on the box (dynamic content).


Thinking about it like this can really help you analyse your app’s content and code and then make informed decisions about how to lay it out.

Loading...

Adam Drake AI Selfie

Written by Adam Drake

Adam Drake is a Frontend React Developer who is very passionate about the quality of the web. He lives with his wife and three children in Prague in the Czech Republic.

Adam Drakes Site © 2024