Skip to content

Instantly share code, notes, and snippets.

@jimjam88
Created July 13, 2023 10:44
Show Gist options
  • Save jimjam88/1a3c5bf3274fda585d0508eb79f5ba56 to your computer and use it in GitHub Desktop.
Save jimjam88/1a3c5bf3274fda585d0508eb79f5ba56 to your computer and use it in GitHub Desktop.
Update date-fns formatDistanceToNow automatically
import React, {memo, useCallback, useEffect, useRef, useState} from 'react';
import formatDistanceToNow from 'date-fns/formatDistanceToNow';
type TimeAgoProps = {
timestamp: number,
}
const UPDATE_DELTA_MS = 10000; // 10s
const getTimeAgo = (timestamp: number): string => `${formatDistanceToNow(new Date(timestamp))} ago`;
const useTimeAgo = (timestamp: number): string => {
const [time, setTime] = useState<string>(getTimeAgo(timestamp));
const raf = useRef<number>(0);
const last = useRef<number>(0);
const updateTime = useCallback((ts: number = Date.now()): void => {
if ((ts - last.current) >= UPDATE_DELTA_MS) {
const next = getTimeAgo(timestamp);
last.current = ts;
if (next !== time) {
setTime(next);
}
}
raf.current = window.requestAnimationFrame(updateTime);
}, [last.current, setTime, timestamp]);
useEffect(() => {
raf.current = window.requestAnimationFrame(updateTime);
return () => {
window.cancelAnimationFrame(raf.current);
};
}, []);
return time;
};
const TimeAgo: React.FC<TimeAgoProps> = memo(({timestamp}) => {
const time = useTimeAgo(timestamp);
return (
<div className="time-ago">{time}</div>
);
});
export default TimeAgo;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment