CodePark/ questions / Rendering strategies
START PRACTICINGPRACTICE
Frontend question · Next.js › Rendering strategies

What is hydration, what causes hydration errors, and how do you fix them?

Hydration means React attaches event handlers and state to HTML that the server already rendered. A hydration error happens when the first client render does not match the server HTML.

React expects the first render in the browser to produce exactly the same markup as the server. If it doesn't, you get a hydration mismatch error.

Common causes:

  • values that differ between server and client, such as Date.now(), Math.random() or dates formatted for a locale
  • branching on typeof window during render
  • invalid HTML nesting, like a div inside a p
  • browser extensions that change the DOM

Fixes:

  • Render client-only values after mount, inside useEffect.
  • Load browser-only components with next/dynamic and ssr: false, from a Client Component.
  • Fix invalid HTML nesting.
  • For a difference you can't avoid on one element, such as a timestamp, add suppressHydrationWarning to that element.
  • Hydration attaches interactivity to HTML the server already rendered.
  • The first client render must match the server output exactly.
  • Causes include time, randomness, typeof window, invalid nesting and browser extensions.
  • Fix mismatches with useEffect, ssr: false or valid HTML.
  • Use suppressHydrationWarning only for a single element.