useTime
Hook to get the current date and time with customizable update logic.
Usage
tsx
import React from "react";
import useTime from "./useTime";
const Demo: React.FC = () => {
const time = useTime({ interval: 1000 });
return (
<div style={{ fontFamily: "monospace", fontSize: "24px" }}>
Current Time: {time.toLocaleTimeString()}
</div>
);
};
export default Demo;
Installation
sh
pnpm dlx scaflo@latest https://raw.githubusercontent.com/programming-with-ia/vDocs/scaflos/hooks/useTime.json -e %src%/hooks
sh
npx scaflo@latest https://raw.githubusercontent.com/programming-with-ia/vDocs/scaflos/hooks/useTime.json -e %src%/hooks
sh
bunx scaflo@latest https://raw.githubusercontent.com/programming-with-ia/vDocs/scaflos/hooks/useTime.json -e %src%/hooks
sh
yarn dlx scaflo@latest https://raw.githubusercontent.com/programming-with-ia/vDocs/scaflos/hooks/useTime.json -e %src%/hooks
API
▸ useTime(options?
): Date
Hook to get the current date and time with customizable update logic.
Parameters
Name | Type | Description |
---|---|---|
options? | UseTimeProps | Configuration options for interval and update logic. |
Returns
Current date and time.
Type aliases
Ƭ UseTimeProps: Object
Options for configuring the useTime
hook.
Type declaration
Name | Type | Description |
---|---|---|
ignoreUpdate? | (newDate : Date , oldDate : Date ) => boolean | - |
interval? | number | Update interval in milliseconds. |
Hook
ts
import { useState, useEffect } from "react";
type UseTimeProps = {
interval?: number;
ignoreUpdate?: (newDate: Date, oldDate: Date) => boolean;
};
export const useTime = ({
interval = 1000,
ignoreUpdate = (newDate, oldDate) =>
newDate.getMinutes() === oldDate.getMinutes(),
}: UseTimeProps = {}) => {
const [time, setTime] = useState<Date>(new Date());
useEffect(() => {
const tick = () => {
const date = new Date();
if (!ignoreUpdate(date, time)) {
setTime(date);
}
};
const timerId = setInterval(tick, interval);
return () => clearInterval(timerId);
}, [interval, ignoreUpdate, time]);
return time;
};