on master help sign in
bridge/src/lib/useInterval.js
22 lines 559 B history raw
1import { useEffect, useRef } from 'react';
3// via: https://overreacted.io/making-setinterval-declarative-with-react-hooks/
4export default function useInterval(callback, delay) {
5 const savedCallback = useRef();
7 // Remember the latest callback.
8 useEffect(() => {
9 savedCallback.current = callback;
10 }, [callback]);
12 // Set up the interval.
13 useEffect(() => {
14 function tick() {
15 savedCallback.current();
16 }
17 if (delay !== null) {
18 let id = setInterval(tick, delay);
19 return () => clearInterval(id);
20 }
21 }, [delay]);