mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
1import * as React from 'react'
2
3/**
4 * Helper hook to run persistent timers on views
5 */
6export function useTimer(time: number, handler: () => void) {
7 const timer = React.useRef<undefined | NodeJS.Timeout>(undefined)
8
9 // function to restart the timer
10 const reset = React.useCallback(() => {
11 if (timer.current) {
12 clearTimeout(timer.current)
13 }
14 timer.current = setTimeout(handler, time)
15 }, [time, timer, handler])
16
17 // function to cancel the timer
18 const cancel = React.useCallback(() => {
19 if (timer.current) {
20 clearTimeout(timer.current)
21 timer.current = undefined
22 }
23 }, [timer])
24
25 // start the timer immediately
26 React.useEffect(() => {
27 reset()
28 // eslint-disable-next-line react-hooks/exhaustive-deps
29 }, [])
30
31 return [reset, cancel]
32}