Created
November 21, 2023 00:04
-
-
Save AndrewIngram/eeaac2116fb4a63171e76fd532c58cd6 to your computer and use it in GitHub Desktop.
Current time in React without hydration errors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Suspense } from "react"; | |
import CurrentTimeClient from "./CurrentTimeClient"; | |
export default function CurrentTime() { | |
const locale = "en-GB"; | |
const dateConfig = { | |
hour: "numeric", | |
minute: "numeric", | |
second: "numeric", | |
timeZone: "Europe/London", | |
} as const; | |
return ( | |
<Suspense | |
fallback={new Intl.DateTimeFormat(locale, dateConfig).format(new Date())} | |
> | |
<CurrentTimeClient locale={locale} dateConfig={dateConfig} /> | |
</Suspense> | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use client"; | |
import { useEffect, useState, unstable_postpone } from "react"; | |
export default function CurrentTimeClient({ locale, dateConfig }) { | |
const [, setCounter] = useState(0); | |
useEffect(() => { | |
const interval = setInterval(() => { | |
setCounter((prevCounter) => prevCounter + 1); | |
}, 1000); | |
return () => clearInterval(interval); | |
}, []); | |
if (typeof window === "undefined") { | |
unstable_postpone("client only"); | |
} | |
return new Intl.DateTimeFormat(locale, dateConfig).format(new Date()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment