Why does this React component fail to hydrate?
Question
A React clock renders new Date().toLocaleTimeString() during render. The server HTML says 09:00:00. The browser's first React render produces 09:00:01. Why can hydration fail, and how would you keep the clock live?
Show hints (2)
- "COMPARE FIRST RENDERS"
Compare the existing HTML with the first render React expects in the browser.
- "REUSE INITIAL DATA"
Think about a value both environments can read before the browser starts the clock.
Show checked explanation
React expects the first browser render to match the server HTML. Pass the exact initial label from the server and render it on both sides. Start browser-specific time formatting or updates in an effect after hydration.
The mismatched and shared-initial-label paths were exercised against React's hydration behavior.
Walkthrough
The browser first displays the server's 09:00:00. If the first client render computes 09:00:01, React sees different text at the same position. Reuse the serialized label for the first render. An effect can set the current browser time and schedule updates, with cleanup for the timer. Sharing a timestamp alone can still produce different text if locale or time zone differs.
Common mistakes
- Starting the clock during render on both the server and the client.
- Assuming that a shared timestamp guarantees identical formatting across time zones.
- Silencing a mismatch on the whole component instead of making initial output deterministic.
Follow-up questions
- "When can
suppressHydrationWarningbe appropriate?" React provides it as an escape hatch for a small, unavoidable difference on one element. It only goes one level deep, and React does not try to patch mismatched text there. - "Why not use
createRootfor this server-rendered markup?" UsehydrateRootto attach React to existing server-rendered HTML.createRootis for a browser-rendered root.
What a strong answer covers
Explain the first-render requirement, account for locale and time zone, and say when the clock starts updating.
Open in interactive practice deck →