| 1 |
/** This is a custom React hook in a format suggest by Dan Abramov in a blog post here: |
| 2 |
* https://overreacted.io/making-setinterval-declarative-with-react-hooks/. It allows setInterval to be used |
| 3 |
* declaratively in functional React components. |
| 4 |
*/ |
| 5 |
import { useEffect, useRef } from 'react'; |
| 6 |
|
| 7 |
export function useInterval(callback: () => void, delay: number | null) { |
| 8 |
const savedCallback = useRef(() => {}); |
| 9 |
|
| 10 |
useEffect(() => { |
| 11 |
savedCallback.current = callback; |
| 12 |
}, [callback]); |
| 13 |
|
| 14 |
useEffect(() => { |
| 15 |
function tick() { |
| 16 |
savedCallback.current(); |
| 17 |
} |
| 18 |
|
| 19 |
if (delay !== null) { |
| 20 |
const id = setInterval(tick, delay); |
| 21 |
return () => clearInterval(id); |
| 22 |
} |
| 23 |
}, [delay]); |
| 24 |
} |