MediumServer Components📖 Theory Question

What is hydration and what causes hydration errors?

💡

Hint

Attaching React event listeners to server-rendered HTML — mismatch between server and client render causes errors

Full Answer

Hydration is the process of React attaching event listeners and state to server-rendered HTML. React "expects" the client render to produce identical HTML to what the server sent.

Common causes of hydration mismatch:

// ❌ Browser-only APIs in render
function Component() {
  return 
{window.innerWidth}
; // window doesn't exist on server! } // ❌ Rendering different content for logged-in users function Greeting() { return

Hello {localStorage.getItem('name')}

; // localStorage = server-undefined } // ❌ Time/random values function Card() { return

Generated at: {new Date().toISOString()}

; // different each render } function Avatar() { return ; // different random }

Fixes:

// ✅ useEffect for browser-only values (runs client-side only)
function Component() {
  const [width, setWidth] = useState(0);
  useEffect(() => { setWidth(window.innerWidth); }, []);
  return 
{width}
; } // ✅ suppressHydrationWarning for expected mismatches (timestamps)
💡 The suppressHydrationWarning prop should be used sparingly — it hides real errors. Fix the root cause wherever possible.

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint