react
runtime_error
ai_generated
true
Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected server HTML to contain a matching <div> in <div>.
ID: react/hydration-error-undefined
80%Fix Rate
85%Confidence
1Evidence
2023-03-20First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| [email protected] | active | — | — | — |
| [email protected] | active | — | — | — |
| [email protected] | active | — | — | — |
Root Cause
Server-rendered HTML structure differs from client's first render, often due to browser-specific APIs (e.g., localStorage, window) causing different output on client vs server.
generic中文
服务器渲染的 HTML 结构与客户端首次渲染的结构不同,通常是由于浏览器特定的 API(如 localStorage、window)导致客户端和服务器输出不一致。
Official Documentation
https://reactjs.org/docs/hydration.htmlWorkarounds
-
90% success Use dynamic import with { ssr: false } in Next.js for components that rely on browser APIs: `const MyComponent = dynamic(() => import('./MyComponent'), { ssr: false })`
Use dynamic import with { ssr: false } in Next.js for components that rely on browser APIs: `const MyComponent = dynamic(() => import('./MyComponent'), { ssr: false })` -
85% success Ensure client and server render the same markup by checking for browser environment before rendering: `if (typeof window === 'undefined') return null;` or using `useEffect` to set state after mount with a loading state.
Ensure client and server render the same markup by checking for browser environment before rendering: `if (typeof window === 'undefined') return null;` or using `useEffect` to set state after mount with a loading state.
中文步骤
Use dynamic import with { ssr: false } in Next.js for components that rely on browser APIs: `const MyComponent = dynamic(() => import('./MyComponent'), { ssr: false })`Ensure client and server render the same markup by checking for browser environment before rendering: `if (typeof window === 'undefined') return null;` or using `useEffect` to set state after mount with a loading state.
Dead Ends
Common approaches that don't work:
-
Adding suppressHydrationWarning prop to root element
60% fail
This only suppresses the warning, doesn't fix the underlying mismatch. The UI may still flash or break.
-
Using useEffect to set state after mount without conditional rendering
50% fail
Doesn't prevent the initial mismatch during hydration; only fixes subsequent updates.
-
Disabling SSR entirely for the component
40% fail
Overly aggressive; loses SSR benefits and may cause layout shift.