Error - Hydration failed because the initial UI does not match what was renderes on the server를 해결해보자
Next.js 공식문서에 따르면 이럴 때 이 에러가 난다고 한다
Hydration errors can occur from:
- Incorrect nesting of HTML tags
<p>
nested in another<p>
tag<div>
nested in a<p>
tag
- Using checks like
typeof window !== 'undefined'
in your rendering logic - Using browser-only APIs like
window
orlocalStorage
in your rendering logic - Browser extensions modifying the HTML
- Incorrectly configured CSS-in-JS libraries
- Ensure your code is following our official examples
- Incorrectly configured Edge/CDN that attempts to modify the html response, such as Cloudflare Auto Minify
해결방법
- React가 렌더링 되면 그 때 UI도 렌더링을 보장하는 방식
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>;
}