Skip to content

Instantly share code, notes, and snippets.

@freddi301
Created October 11, 2019 09:55
Show Gist options
  • Save freddi301/1b2356a9c3ee00ae4a2efe221fdf9abc to your computer and use it in GitHub Desktop.
Save freddi301/1b2356a9c3ee00ae4a2efe221fdf9abc to your computer and use it in GitHub Desktop.
useExpiration: returns true if given timestamp is in the future #react #hook
import { useState, useEffect } from "react";
/** @description hook: returns true if given timestamp is in the future */
export function useExpiration(
timestamp: number | null | undefined,
): boolean {
const visible = timestamp != null && Date.now() <= timestamp;
const [, forceRerender] = useState(0);
useEffect(() => {
if (visible && timestamp != null) {
const timeoutId = setTimeout(
forceRerender,
Math.max(0, timestamp - Date.now()),
increment,
);
return () => {
clearTimeout(timeoutId);
};
}
return;
}, [visible, timestamp]);
return visible;
}
function increment(count: number): number {
return count + 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment