20 lines
435 B
TypeScript
20 lines
435 B
TypeScript
import { useEffect, useRef } from 'react'
|
|
|
|
export const useInterval = (callback: () => void, delay: number) => {
|
|
const savedCallback = useRef(callback)
|
|
|
|
useEffect(() => {
|
|
savedCallback.current = callback
|
|
}, [callback])
|
|
|
|
useEffect(() => {
|
|
function tick() {
|
|
savedCallback.current()
|
|
}
|
|
if (delay !== null) {
|
|
const id = setInterval(tick, delay)
|
|
return () => clearInterval(id)
|
|
}
|
|
}, [delay])
|
|
}
|