Changeset View
Changeset View
Standalone View
Standalone View
web/cashtab/src/hooks/useInterval.js
import { useRef, useEffect } from 'react'; | import { useEffect, useRef } from 'react'; | ||||
const useInterval = (callback, delay) => { | // https://overreacted.io/making-setinterval-declarative-with-react-hooks/ | ||||
function useInterval(callback, delay) { | |||||
const savedCallback = useRef(); | const savedCallback = useRef(); | ||||
// Remember the latest callback. | |||||
useEffect(() => { | useEffect(() => { | ||||
savedCallback.current = callback; | savedCallback.current = callback; | ||||
}); | }, [callback]); | ||||
// Set up the interval. | |||||
useEffect(() => { | useEffect(() => { | ||||
function tick() { | function tick() { | ||||
savedCallback.current(); | savedCallback.current(); | ||||
} | } | ||||
if (delay !== null) { | |||||
let id = setInterval(tick, delay); | let id = setInterval(tick, delay); | ||||
return () => clearInterval(id); | return () => clearInterval(id); | ||||
} | |||||
}, [delay]); | }, [delay]); | ||||
}; | } | ||||
export default useInterval; | export default useInterval; |