26 lines
560 B
TypeScript
26 lines
560 B
TypeScript
|
import { useEffect, useRef } from 'react'
|
||
|
|
||
|
export default function useInterval(callback: () => void, delay: null | number) {
|
||
|
const savedCallback = useRef<() => void>()
|
||
|
|
||
|
// Remember the latest callback.
|
||
|
useEffect(() => {
|
||
|
savedCallback.current = callback
|
||
|
return () => {
|
||
|
}
|
||
|
}, [callback])
|
||
|
|
||
|
// Set up the interval.
|
||
|
useEffect(() => {
|
||
|
function tick() {
|
||
|
savedCallback.current()
|
||
|
}
|
||
|
|
||
|
if (delay !== null) {
|
||
|
let id = setInterval(tick, delay)
|
||
|
return () => clearInterval(id)
|
||
|
}
|
||
|
return () => {
|
||
|
}
|
||
|
}, [delay])
|
||
|
}
|