Skip to content

Commit 40bf9cd

Browse files
add: useTime
1 parent bd47ff3 commit 40bf9cd

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

demos/useTime.tsx

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import React from "react";
2+
import useTime from "./useTime";
3+
4+
const Demo: React.FC = () => {
5+
const time = useTime({ interval: 1000 });
6+
7+
return (
8+
<div style={{ fontFamily: "monospace", fontSize: "24px" }}>
9+
Current Time: {time.toLocaleTimeString()}
10+
</div>
11+
);
12+
};
13+
14+
export default Demo;

hooks/useTime.ts

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import { useState, useEffect } from "react";
2+
3+
/**
4+
* Options for configuring the `useTime` hook.
5+
*/
6+
type UseTimeProps = {
7+
/** Update interval in milliseconds. */
8+
interval?: number;
9+
10+
/** Function to skip updates based on custom logic. */
11+
ignoreUpdate?: (newDate: Date, oldDate: Date) => boolean;
12+
};
13+
14+
/**
15+
* Hook to get the current date and time with customizable update logic.
16+
* @param {UseTimeProps} [options] - Configuration options for interval and update logic.
17+
* @returns {Date} Current date and time.
18+
* @public
19+
* @see [Documentation](https://programming-with-ia.github.io/vDocs/hooks/use-time)
20+
* @example
21+
* ```tsx
22+
* const time = useTime({ interval: 1000 });
23+
* console.log(time.toLocaleTimeString());
24+
* ```
25+
*/
26+
const useTime = ({
27+
interval = 1000,
28+
ignoreUpdate = (newDate, oldDate) =>
29+
newDate.getMinutes() === oldDate.getMinutes(),
30+
}: UseTimeProps = {}) => {
31+
const [time, setTime] = useState<Date>(new Date());
32+
33+
useEffect(() => {
34+
const tick = () => {
35+
const date = new Date();
36+
if (!ignoreUpdate(date, time)) {
37+
setTime(date);
38+
}
39+
};
40+
41+
const timerId = setInterval(tick, interval);
42+
43+
return () => clearInterval(timerId);
44+
}, [interval, ignoreUpdate, time]);
45+
46+
return time;
47+
};
48+
49+
export default useTime;

0 commit comments

Comments
 (0)