@react-hookz/web
Version:
React hooks done right, for browser and SSR.
53 lines (52 loc) • 1.8 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useRafCallback = void 0;
var react_1 = require("react");
var __1 = require("..");
var const_1 = require("../util/const");
/**
* Makes passed function to be called within next animation frame.
*
* Consequential calls, before the animation frame occurred, cancel previously scheduled call.
*
* @param cb Callback to fire within animation frame.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function useRafCallback(cb) {
var cbRef = (0, __1.useSyncedRef)(cb);
var frame = (0, react_1.useRef)(0);
var cancel = (0, react_1.useCallback)(function () {
if (!const_1.isBrowser)
return;
if (frame.current) {
cancelAnimationFrame(frame.current);
frame.current = 0;
}
}, []);
(0, __1.useUnmountEffect)(cancel);
return [
(0, react_1.useMemo)(function () {
var wrapped = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (!const_1.isBrowser)
return;
cancel();
frame.current = requestAnimationFrame(function () {
cbRef.current.apply(cbRef, args);
frame.current = 0;
});
};
Object.defineProperties(wrapped, {
length: { value: cb.length },
name: { value: "".concat(cb.name || 'anonymous', "__raf") },
});
return wrapped;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []),
cancel,
];
}
exports.useRafCallback = useRafCallback;