UNPKG

use-watch

Version:

A react hook that use to calling the callback when a part of dependencies changed

10 lines (8 loc) 973 B
/** * Bundle of use-watch * Generated: 2021-10-10 * Version: 1.1.1 * License: MIT * Author: 2631541504@qq.com */ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):(e=e||self).useWatch=t(e.React)}(this,function(t){"use strict";return function(r,e){var c=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{},n=t.useRef({lastCall:0,throttle:c.throttle,debounce:c.debounce,timer:null}),u=t.useRef(c.immediate),o=t.useRef({preWatches:void 0,watcher:e});o.current.watcher=e,t.useLayoutEffect(function(){function e(){try{o.current.watcher(r,o.current.preWatches),n.current.lastCall=t}catch(e){console.error(e)}}var t=Date.now();u.current&&(c.debounce?(clearTimeout(n.current.timer),n.current.timer=setTimeout(e,c.debounce)):(!c.throttle||c.throttle&&t-n.current.lastCall>c.throttle)&&e()),o.current.preWatches=r,u.current=!0},[c.debounce,c.throttle,r])}});