128
AAlfréd Nagy·Közzétéve over 1 year ago

Hydration error in Next.js 14 with server components

typescript
bug
nextjs
I'm building a forum website with Next.js 14 and I'm running into a persistent hydration error. The issue seems to be related to using `new Date()` on the server and client, causing a mismatch. The error is `Text content does not match server-rendered HTML.` Here's the component that's causing the problem:

function PostTimestamp({ time }) {
  return {new Date(time).toLocaleTimeString()};
}
I thought Next.js handled this automatically. What is the standard way to handle timestamps or other dynamic values that can differ between server and client? I've tried using `useEffect` to set the state on the client, but it feels like a workaround. Is there a more idiomatic Next.js way?

2 Hozzászólás

C
Csaba Fekete·over 1 year ago

Exactly what @Boglárka said. Another option is to pass the formatted string directly from the server component to the client component as a prop, if the format doesn't need to adapt to the client's locale on the fly. But for dynamic, client-specific formatting, `useEffect` is the way.

B
Boglárka Varga·over 1 year ago

This is a classic issue. The problem is that the server renders the page at a specific time, and the client renders it moments later. Even a millisecond difference will cause `toLocaleTimeString()` to produce different output. You should render a placeholder on the server or a static string, and then mount the client-side-only component with the actual time in a `useEffect`.