Solving Hydration Error in React.js/Next.js

Solving Hydration Error in React.js/Next.js

·

2 min read

How to solve the Hydration error ?

I think that you are already looking for the solution and you already know what this error is so let's get directly to the solution and leave the boring explanation part for later or if you want it much faster I have a 1 min video on the same check below. The best way to solve the hydration error in Next.js is to use the command below.

Let me demonstrate using the example image below. Just look at this Navbar component.

Copy and paste just like line 5 in above image which is given below in your component.

import dynamic from "next/dynamic";

Copy and paste the below code just like on line 23 in the above image. Make sure to do this wherever you are trying to export default the function.

export default dynamic (() => Promise.resolve(Navbar), {ssr: false})

I just used this on Navbar here. You can use this on any component. Also, I had only to do it for my Navbar component once. I needn't do it for every single component. Instead of Navbar whichever component name is there use that same component name in the export default function.

What is Hydration error ?

Just as in the Image above the Hydration error involves always showing 3 error. I literally have looked to solve it for literally weeks. Hydration error occurs when you are trying to deploy your website anywhere. It might even come when you try to deploy project on localhost.

It occurs for 2 main reasons

  • If you have some tags which are impossible to use something like using a <div> tag inside a <p> tag which shouldn't be possible.

  • A hydration error occurs when a React component is rendered on the server side and then attempts to be re-rendered on the client side. This can happen if the initial rendering on the server side does not match the expected state of the component on the client side.

If for some reason it still doesn't work. go to the above StackOverflow and check the example where they did the same but instead of Navbar they made the changes to _app.js folder.

import dynamic from "next/dynamic";

export default dynamic (() => Promise.resolve(App), {ssr: false})