Hydration for Dummies
Rutunj Parikh
Posted on August 3, 2022
Understanding what Hydration is and understanding how to handle the error it generates in React
Not long ago did I start using Next.js considering its features like inbuilt routing which frees you from worrying about having a Router Dependency. This is just one of the many features of Next, however, this article is not about discussing the features of Next.js but pinpointing a silly mistake that I made at the beginning.
Before Moving on to the meat of the blog, I'd like to define a few terminologies so that the reader has the same context.
What is React?
For the scope of this very blog, I’ll define react as a reconciliation algorithm(finds differences between virtual DOM and the actual DOM).
The difference can be an addition or removal or rearrangement of a Node in the DOM.
What is Virtual-DOM?
A copy of the actual DOM that a Framework uses during Reconciliation. It is also used by other technologies like Vue.js and Elm.
There are rendering methods(SSR, SSG,...) that one should know to better understand but I’ll try to go further assuming the reader has minimal to no knowledge.
I'm attaching this excellent video explaining the same. However, feel free to skip the video and read further.
Data Fetching with Next.js by Lee Robinson
Why Hydration?
Imagine having a slow internet connection and surfing the internet, u find this article. it’ll take long. how long.? Maybe long enough to piss you off.
What if there were some kind of text being displayed? That’d be better. At least you had something to read in the meanwhile
servers already have this raw version of each page.
Such fetching is a common sight and helps provide a richer User Experience.
After you can see the raw text/skeleton/layout of the page, incrementally the interactivity to the page would load. (event listeners, styles, etc ).
This addition of interactivity is called HYDRATION.
Also, have a break. Get a glass of water. You deserve it.
Creating Hydration error
Here I have a Next app created using
npx create-next-app
The app works fine just as expected.
After working on a few projects myself, I've had the error
NEXT provides this window where we can see the errors for a better dev experience. However, most of the time such Hydration errors are caused by the incorrect usage/placement of HTML Tags.
Often it pops up while a
tag or any typography tag is used as a wrapper for other components. Which is what I did to recreate this error.
Also, it might not appear in the error overlay. And this is what had me strangled before I realized to have a look at the console which pointed it out more explicitly
Hope you've learned something new.
Thanks!
Posted on August 3, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.