Files
the-biergarten-app/hooks/useTimeDistance.ts
Aaron William Po a4362a531c Add custom hooks for time distance and retrieving like count
Documentation added to all custom hooks
2023-04-03 23:32:32 -04:00

21 lines
784 B
TypeScript

import formatDistanceStrict from 'date-fns/formatDistanceStrict';
import { useState, useEffect } from 'react';
/**
* Returns the time distance between the provided date and the current time, using the
* `date-fns` `formatDistanceStrict` function. This hook ensures that the same result is
* calculated on both the server and client, preventing hydration errors.
*
* @param createdAt The date to calculate the time distance from.
* @returns The time distance between the provided date and the current time.
*/
const useTimeDistance = (createdAt: Date) => {
const [timeDistance, setTimeDistance] = useState('');
useEffect(() => {
setTimeDistance(formatDistanceStrict(createdAt, new Date()));
}, [createdAt]);
return timeDistance;
};
export default useTimeDistance;