The Symptom
Symptom
Root Cause Analysis
Root Cause
We were displaying the user's local time for an upcoming flash sale using `new Date().toLocaleTimeString()`. The Next.js server rendered the page in UTC ("10:30 AM"). When the React bundle hydrated on the client's browser (which was in EST), the client calculated "14:30 PM". React 18's strict hydration caught the mismatch. Because it couldn't reconcile the differences, it bailed out of hydration and completely destroyed and re-rendered the entire component tree.
// The fatal flaw: Relying on browser-specific state during initial render
const FlashSaleTimer = () => {
const [time, setTime] = useState(new Date().toLocaleTimeString());
return <div>Sale ends at: {time}</div>;
};
Resolution
Resolution
// The fix: Two-pass rendering
const FlashSaleTimer = () => {
const [isMounted, setIsMounted] = useState(false);
useEffect(() => setIsMounted(true), []);
if (!isMounted) return <div>Sale ends at: --:--</div>;
return <div>Sale ends at: {new Date().toLocaleTimeString()}</div>;
};
Discussions 0