Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

RelativeTime.tsx

21 lines782 Bytes

1import { useSyncExternalStore } from "react";
2import { msUntilRelativeTimeChange, relativeTime } from "../lib/time";
3​
4// The React Compiler caches inline relativeTime calls on the timestamp alone.
5export function RelativeTime(props: { timestamp: string }) {
6 const subscribe = (onChange: () => void) => {
7 let timer: ReturnType<typeof setTimeout> | undefined;
8 const schedule = () => {
9 const delayMs = msUntilRelativeTimeChange(props.timestamp);
10 if (delayMs === null) return;
11 timer = setTimeout(() => {
12 onChange();
13 schedule();
14 }, delayMs);
15 };
16 schedule();
17 return () => clearTimeout(timer);
18 };
19 const getSnapshot = () => relativeTime(props.timestamp);
20 return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);