Repository navigation
Summaryi'm building a dashboard feature in Next.js (App Router) and trying to display the current user's local registration date. However, I keep getting this error in my browser console : here's my simple component inside app/page.tsx : Additional informationexport default function Page() {
const formattedDate = new Date().toLocaleDateString();
return <div>Registered on: {formattedDate}</div>;
}ExampleNo response |
Replies: 3 comments 3 replies
|
This happens because the text rendered during SSR has to match the text React produces on the first browser render. Also, for a registration date you probably do not want For a user-local display, keep the page as a Server Component and move only the formatting into a small Client Component: // app/local-registration-date.tsx
'use client'
import { startTransition, useEffect, useState } from 'react'
export function LocalRegistrationDate({ date }: { date: string }) {
const [label, setLabel] = useState<string | null>(null)
useEffect(() => {
startTransition(() => {
setLabel(
new Date(date).toLocaleDateString(undefined, {
year: 'numeric',
month: 'long',
day: 'numeric',
})
)
})
}, [date])
return (
<time dateTime={date} suppressHydrationWarning>
{label ?? '...'}
</time>
)
}Then in the page: import { LocalRegistrationDate } from './local-registration-date'
export default async function Page() {
const registeredAt = '2026-06-21T10:00:00Z' // replace with user.createdAt
return (
<div>
Registered on: <LocalRegistrationDate date={registeredAt} />
</div>
)
}The important part is that the initial render is deterministic ( |
|
hi! this hydration error happens because the server renders the time using the server's time zone (e.g., UTC) during SSR, but when the browser receives the HTML, it tries to re-render using your local machine's time zone. Since the strings don't match, React throws a hydration mismatch error. here are the two best ways to solve this in Next.js depending on your needs: my solution is to use 'use client';
import { useEffect, useState } from 'react';
export default function Page() {
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
const formattedDate = new Date().toLocaleDateString();
return (
<div>
Registered on: {mounted ? formattedDate : 'Loading...'}
</div>
);
} |
|
See also https://nextjs.org/docs/app/guides/preventing-flash-before-hydration#dates-and-formatting |
This happens because the text rendered during SSR has to match the text React produces on the first browser render.
new Date().toLocaleDateString()is not stable for that: it depends on the current time, locale, and time zone. The Next.js hydration-error docs list time-dependent APIs likeDate()in render as a common cause.Also, for a registration date you probably do not want
new Date()there; use the actual stored registration timestamp and format that.For a user-local display, keep the page as a Server Component and move only the formatting into a small Client Component: