The "Hydration failed" error in Next.js, especially with relative timestamps like "2 hours ago," is a common issue. It occurs because the HTML generated on the server for the relative time string does not precisely match what the client-side React code attempts to render during hydration. This mismatch often stems from:
- Time Discrepancies: The server's clock and the client's clock (or their respective timezones/moment of render) can differ by a few seconds or minutes.
- Render Time: The exact moment the string is generated on the server versus when it's generated on the client after hydration can lead to a slight difference in "ago" calculations (e.g., "1 hour ago" vs. "59 minutes ago").
To effectively handle relative timestamps and avoid hydration errors, you should ensure that the dynamic, time-sensitive parts of your UI are rendered consistently or only on the client.
Here are the best approaches:
1. Client-Side Rendering for Dynamic Content (Recommended)
The most robust solution is to render the dynamic "time ago" string exclusively on the client after the component has mounted. This ensures that the server renders a consistent placeholder (or nothing), and the actual time calculation happens only where the time is truly known and stable: the client's browser.
Implementation Steps:
- Introduce State: Use React's hook to manage the relative time string.