@react-hookz/web
Version:
React hooks done right, for browser and SSR.
22 lines (21 loc) • 813 B
JavaScript
import { useEffect } from 'react';
import { useSyncedRef } from "../useSyncedRef/useSyncedRef.js";
/**
* Like `setInterval` but in form of react hook.
*
* @param callback Callback to be called within interval.
* @param ms Interval delay in milliseconds, `undefined` disables the interval.
* Keep in mind, that changing this parameter will re-set interval, meaning
* that it will be set as new after the change.
*/
export function useIntervalEffect(callback, ms) {
var cbRef = useSyncedRef(callback);
useEffect(function () {
if (!ms && ms !== 0) {
return;
}
var id = setInterval(function () { return cbRef.current(); }, ms);
return function () { return clearInterval(id); };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ms]);
}