useInterval.ts 447 B

1234567891011121314151617181920212223
  1. import { useEffect, useRef } from 'react'
  2. export function useInterval(callback: () => void, delay: number | false) {
  3. const savedCallback = useRef(callback)
  4. useEffect(() => {
  5. savedCallback.current = callback
  6. }, [callback])
  7. useEffect(() => {
  8. if (delay === false) {
  9. return
  10. }
  11. const id = setInterval(() => {
  12. savedCallback.current()
  13. }, delay)
  14. return () => {
  15. clearInterval(id)
  16. }
  17. }, [delay])
  18. }