Written on 2023-03-08 by Adam Drake - 3 min read
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:
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.
This was my code before:
This was my code after:
Now the error has gone away!
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 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