Skip to content

Instantly share code, notes, and snippets.

@AndrewIngram
Created November 21, 2023 00:04
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrewIngram/eeaac2116fb4a63171e76fd532c58cd6 to your computer and use it in GitHub Desktop.
Save AndrewIngram/eeaac2116fb4a63171e76fd532c58cd6 to your computer and use it in GitHub Desktop.
Current time in React without hydration errors
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>
);
}
"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