Last active
March 31, 2023 04:37
-
-
Save akhrszk/776e7f136f8c167d9e66adff1a2d63e5 to your computer and use it in GitHub Desktop.
React Hooks for using setInterval
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useRef, useState } from 'react'; | |
type Control = { | |
start: () => void; | |
stop: () => void; | |
}; | |
type State = 'RUNNING' | 'STOPPED'; | |
type Fn = () => void; | |
export const useInterval = (fn: Fn, interval: number, autostart = true): [State, Control] => { | |
const onUpdateRef = useRef<Fn>(); | |
const [state, setState] = useState<State>('STOPPED'); | |
const start = () => { | |
setState('RUNNING'); | |
}; | |
const stop = () => { | |
setState('STOPPED'); | |
}; | |
useEffect(() => { | |
onUpdateRef.current = fn; | |
}, [fn]); | |
useEffect(() => { | |
if (autostart) { | |
setState('RUNNING'); | |
} | |
}, [autostart]); | |
useEffect(() => { | |
let timerId: NodeJS.Timeout | undefined; | |
if (state === 'RUNNING') { | |
timerId = setInterval(() => { | |
onUpdateRef.current?.(); | |
}, interval); | |
} else { | |
timerId && clearInterval(timerId); | |
} | |
return () => { | |
timerId && clearInterval(timerId); | |
}; | |
}, [interval, state]); | |
return [state, { start, stop }]; | |
}; | |
export default useInterval; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@akhrszk
https://zenn.dev/akhr_s/articles/065e18ab3c4883
こちら見て参考にさせていただきました、ありがとうございます…!
すごく細かいのですが1点、
は
でないと、autostartの値に関わらずsetIntervalがはじまってしまうのではないかと思いました!
(見当違いであった場合ご放念ください!)