seenfil
Back to feed

How to fix "Hydration failed because the initial UI does not match" in React & Next.js?

I keep running into the classic React hydration error: 'Hydration failed because the initial UI does not match that rendered on the server'. It seems to trigger randomly when rendering dynamic timestamps and localStorage items on initial page load.

What is the cleanest, production-ready pattern to prevent hydration mismatches without disabling SSR completely?
48
Comments (3)
This happens because the server generates HTML with one state (e.g. UTC timestamp or empty storage), while the client executes with local browser state immediately during hydration.

Here are the 3 best ways to fix it:
1. Use a mounted flag with useEffect:
javascript
const [isMounted, setIsMounted] = useState(false);
useEffect(() => { setIsMounted(true); }, []);
if (!isMounted) return <SkeletonLoader />;

2. For specific dynamic text (like dates), wrap with suppressHydrationWarning={true} on that element.
3. In Next.js, use dynamic imports with SSR disabled for browser-only components:
const NoSSR = dynamic(() => import('../components/Widget'), { ssr: false });
Option 1 is what we use in our SaaS. Just make sure not to abuse suppressHydrationWarning on high-level container divs, as it can hide actual layout bugs. The useEffect mounted hook is reliable and prevents flash of unstyled content.
kesha reply
Totally agree! You can also use inline useState or a quick helper:
javascript
const isClient = typeof window !== 'undefined';

Works like a charm! 🔥
Log in to leave a comment.
Photo
1 / 1
likes
❤️ 🔥 😂 😍 👍 👏 🎉 🚀 🥳 💯

Create Post