The Problem
Error: Hydration failed because the initial UI does not match
what was rendered on the server.
Why This Happens
Server-rendered HTML differs from client-rendered HTML. Common causes:
- Date/time formatting
- Browser-only APIs
- Random values
- User-specific data
Solution 1: Suppress Hydration Warning
// For timestamps
<time suppressHydrationWarning>
{new Date().toLocaleString()}
</time>
Solution 2: useEffect for Client-Only Code
'use client';
import { useState, useEffect } from 'react';
export default function ClientTime() {
const [time, setTime] = useState('');
useEffect(() => {
setTime(new Date().toLocaleString());
}, []);
if (!time) return null; // or skeleton
return <span>{time}</span>;
}
Solution 3: Dynamic Import with ssr: false
import dynamic from 'next/dynamic';
const ClientOnlyChart = dynamic(
() => import('./Chart'),
{ ssr: false }
);
Solution 4: Check for Browser Environment
'use client';
export default function BrowserOnly({ children }) {
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
if (!mounted) return null;
return children;
}
Best Practices
- Keep Server Components as default
- Use 'use client' only when needed
- Move browser APIs to useEffect
- Use consistent date formatting
Comments (0)
Leave a Comment
No comments yet. Be the first to share your thoughts!