rooks
Version:
Essential React custom hooks ⚓ to super charge your components!
46 lines (45 loc) • 1.35 kB
JavaScript
import raf from "raf";
import { useRef, useEffect } from "react";
import { noop } from "../utils/noop";
/**
*
* useRaf
* Uses a polyfilled version of requestAnimationFrame
*
* @param {Function} callback The callback function to be executed
* @param {boolean} [isActive] The value which while true, keeps the raf running infinitely
* @see https://react-hooks.org/docs/useRaf
*/
export function useRaf(callback, isActive) {
var savedCallback = useRef();
// Remember the latest function.
useEffect(function () {
savedCallback.current = callback;
}, [callback]);
useEffect(function () {
var animationFrame;
var startTime = Date.now();
function tick() {
var _a;
var timeElapsed = Date.now() - startTime;
startTime = Date.now();
loop();
(_a = savedCallback.current) === null || _a === void 0 ? void 0 : _a.call(savedCallback, timeElapsed);
}
function loop() {
animationFrame = raf(tick);
}
if (isActive) {
startTime = Date.now();
loop();
return function () {
if (animationFrame) {
raf.cancel(animationFrame);
}
};
}
else {
return noop;
}
}, [isActive]);
}