|
1 | | -import { useState, useEffect, useRef } from 'react'; |
| 1 | +import { useState } from 'react'; |
2 | 2 | import { Time } from './utils'; |
| 3 | +import { useInterval } from './hooks'; |
3 | 4 |
|
4 | | -export default function useStopwatch(settings) { |
5 | | - const { autoStart, offsetTimestamp } = settings || {}; |
6 | | - |
| 5 | +export default function useStopwatch({ autoStart, offsetTimestamp }) { |
7 | 6 | const [seconds, setSeconds] = useState(Time.getSecondsFromExpiry(offsetTimestamp || 0)); |
8 | 7 | const [isRunning, setIsRunning] = useState(autoStart); |
9 | | - const intervalRef = useRef(); |
10 | 8 |
|
11 | | - function clearIntervalRef() { |
12 | | - if (intervalRef.current) { |
13 | | - setIsRunning(false); |
14 | | - clearInterval(intervalRef.current); |
15 | | - intervalRef.current = undefined; |
16 | | - } |
17 | | - } |
| 9 | + useInterval(isRunning ? () => { |
| 10 | + setSeconds((prevSeconds) => (prevSeconds + 1)); |
| 11 | + } : () => {}, 1000); |
18 | 12 |
|
19 | 13 | function start() { |
20 | | - if (!intervalRef.current) { |
21 | | - setIsRunning(true); |
22 | | - intervalRef.current = setInterval(() => setSeconds((prevSeconds) => (prevSeconds + 1)), 1000); |
23 | | - } |
| 14 | + setIsRunning(true); |
24 | 15 | } |
25 | 16 |
|
26 | 17 | function pause() { |
27 | | - clearIntervalRef(); |
| 18 | + setIsRunning(false); |
28 | 19 | } |
29 | 20 |
|
30 | 21 | function reset(offset: number) { |
31 | | - clearIntervalRef(); |
| 22 | + setIsRunning(autoStart); |
32 | 23 | setSeconds(Time.getSecondsFromExpiry(offset || 0)); |
33 | | - if (autoStart) { |
34 | | - start(); |
35 | | - } |
36 | 24 | } |
37 | 25 |
|
38 | | - // didMount effect |
39 | | - useEffect(() => { |
40 | | - if (autoStart) { |
41 | | - start(); |
42 | | - } |
43 | | - return clearIntervalRef; |
44 | | - }, []); |
45 | | - |
46 | 26 | return { |
47 | 27 | ...Time.getTimeFromSeconds(seconds), start, pause, reset, isRunning, |
48 | 28 | }; |
|
0 commit comments