一、基础
参考以前写的博客:https://www.cnblogs.com/gg-qq/p/11249200.html
二、react中实现防抖和节流的hooks
手写可靠的useDebounce:
export function useDebounce(fn, delay) {
const { current } = useRef({});
function f(...args) {
if (current.timer) {
clearTimeout(current.timer);
}
current.timer = setTimeout(fn.bind(undefined, ...args), delay);
}
return f;
}
useThrottle:
export function useThrottle(fn, delay) {
const { current } = useRef({});
function f(...args) {
if (!current.timer) {
current.timer = setTimeout(() => {
delete current.timer;
}, delay);
fn(...args);
}
}
return f;
}
三、创建唯一的debounce,防止重复调用函数
使用useCallback,由于创建之后useCallback从不刷新,它内部的state一直不变 (内部进行setter会改变外部state)
const load = useCallback(
debounce(() => loadList(), 500),
[],
);
使用UseRef,保存函数,终身存在
const load = useRef(
debounce(() => loadList(), 500),
[],
);