Common Cause: Random Values and Timestamps
You'll learn why functions like Math.random(), Date.now(), and uuid() break hydration and how to avoid them.
The Core Problem
When React renders your component on the server, it generates HTML. When that same component hydrates on the client, React expects to produce identical output. But functions like Math.random(), Date.now(), or unique ID generators produce different values each time they run.
Server render at 10:00:01 AM generates one timestamp. Client hydration at 10:00:03 AM generates a different timestamp. React sees the mismatch and throws a hydration error.
Why This Happens
function BlogPost() {
// ❌ WRONG: Different value on server vs client
const id = Math.random();
const timestamp = Date.now();
return <div id={id}>Posted at {timestamp}</div>;
}
On the server, Date.now() might return 1704067201000. By the time the client hydrates (even milliseconds later), Date.now() returns 1704067203000. React detects the mismatch between server HTML and client render.
The Rule
Non-deterministic functions during render break hydration. The server and client must produce identical output given identical props and state.
The Solution Pattern
Move time-sensitive or random values to after hydration completes—inside useEffect, event handlers, or use server-provided values as props:
// ✅ CORRECT: Use value from server as prop
function BlogPost({ serverTimestamp }) {
return <div>Posted at {serverTimestamp}</div>;
}
Key Takeaway: Functions that produce different outputs on each call (Math.random(), Date.now(), uuid()) cause hydration mismatches because the server and client execute at different times. Always use deterministic values during initial render or defer random/time-based values until after hydration.