Resolving Hydration Failed Error

힘센캥거루
2024년 12월 16일(수정됨)
70
nextjs

1. Issue Discovery

While browsing the school meal site I created, I suddenly encountered the following issue.

Ah... I can't stand these issues...

Resolving Hydration Failed Error-1

Clicking through, it turned out to be a 'Hydration failed' message.

To summarize, it means the page rendered by the server is different from the one the client sees.

The causes can be varied according to the documentation.

Resolving Hydration Failed Error-2

2. Official Documentation

Next.js Official Documentation identifies the causes of hydration errors as follows:

  1. Incorrect use of HTML tags

    1. Nesting <p> tags within a <p> tag

    2. Nesting <div> tags within a <p> tag

    3. Nesting <ul> or <ol> within a <p> tag

  2. Using logic like typeof window !== 'undefined'

  3. Using browser APIs like window or localStorage in rendering logic

  4. Using time-dependent APIs like Date() in rendering logic

  5. Browser extensions that modify HTML

  6. Improper CSS in JS libraries

  7. Misconfigured Edge/CDN attempting to modify HTML responses like Cloudflare auto-minify

But no matter how much I looked, none of these applied to me.

So, I debugged from start to finish.

3. Debugging Process

I commented out and saved each line of code to find the broken part.

Wow, this must be why we develop in dev environments.

Resolving Hydration Failed Error-3

Eventually, I discovered the error occurred in the Lunch component...

I figured it out...

So, I went into Lunch and commented out each part again.

Resolving Hydration Failed Error-4

Strangely, input tags were the cause of the hydration failed error.

I experimented in various ways, and every className hiding elements like scale-0, opacity-0 caused the error!

Changing it was annoying and unsatisfactory.

4. Solution

Resolving Hydration Failed Error-5

Ignoring such pointless errors is the answer.

Even trivial things can cause issues

Add the suppressHydrationWarning attribute to the element.

Resolving Hydration Failed Error-6

After doing this, there are no errors.

5. Review

I struggled as there were no similar cases.

Teaching myself coding sometimes leads to taking the long way around for simple problems.

I hope this article helps at least a little.

댓글을 불러오는 중...