Next.js에서 수화 오류를 해결하는 방법

WBOY
풀어 주다: 2024-09-06 21:00:18
원래의
923명이 탐색했습니다.

How to Solve Hydration Errors in Next.js

"Hydration failed because the server-rendered HTML did not match the client...."

If you've been using Next.js to build applications, you must have gotten the above error or something similar. It is called Hydration Error.

I used to get this error when I first started out with Next.js but didn't know what to do and never cared to look it up because it wasn't really affecting my code at the time. Not until I was asked by an interviewer, what I'd do to solve an hydration error in Next.js. I was dumbfounded because now it was not a case of the interviewer trying to bring me down, but a case of nonchalance and sheer ignorance. I don't want you to be like me in your next interview. So let's discuss on Hydration.

Hydration is the process where static HTML becomes interactive by adding Javascript to it. So normally when a webpage is rendered on the server, it loses its interactivity and event handlers before getting to the client. React is responsible for building the component tree on the client. This is called hydration, because it adds the interactivity and event handlers that were lost when the HTML was server-side rendered. React compares it with the actual server-side rendered DOM. They must be the same so React can adopt it.

If there is a mismatch between the page we have and what the client-side thinks we should have, we get a "Hydration Error." Some common hydration error causes include: Incorrect HTML element nesting, different data used for rendering, using browser-only APIs, side effects, etc.

Whatever the cause, you'd have to figure it out by reading the error message that you get. Possible solutions include;

1. Using useEffect to run on the client only.
To prevent a hydration mismatch, make sure the component renders the same content on the server-side as it does on the initial client-side render. You can use the useEffect hook to intentionally render content on the client. See example below:

import { useState, useEffect } from 'react'

export default function App() {
  const [isClient, setIsClient] = useState(false)

  useEffect(() => {
    setIsClient(true)
  }, [])

  return <h1>{isClient ? 'This is never prerendered' : 'Prerendered'}</h1>
}
로그인 후 복사

2. Disabling server-side rendering on specific components.
You can use the disable prerendering feature on Next.js on specific components. This can prevent hydration mismatches. See example below:

import dynamic from 'next/dynamic'

const NoSSR = dynamic(() => import('../components/no-ssr'), { ssr: false })

export default function Page() {
  return (
    <div>
      <NoSSR />
    </div>
  )
}
로그인 후 복사

3. Using Suppress Hydration Warning
There are times when content will inevitably be different on the server and client, instances like timestamp. What you can do is to silence the hydration mismatch warning by adding suppressHydrationWarning={true} to the element.

So with these three methods, you should be able to resolve that hydration error the next time it pops up when building on Next.js.

Don't forget to subscribe to my page to get more eye-opening content on Programming.

위 내용은 Next.js에서 수화 오류를 해결하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿