封装防抖
import React, { useRef, useEffect, useCallback } from 'react';
function useDebounce(fn, delay) {
const delayRef = useRef(delay);
const fnRef = useRef(fn);
// 更新ref值
useEffect(() => {
delayRef.current = delay;
}, [delay]);
useEffect(() => {
fnRef.current = fn;
}, [fn]);
const debounced = useRef();
// 防抖函数
const debounce = useCallback((...args) => {
const later = () => {
debounced.current = null;
};
clearTimeout(debounced.current);
debounced.current = setTimeout(() => {
fnRef.current(...args);
later();
}, delayRef.current);
}, []);
useEffect(
() => () => {
clearTimeout(debounced.current);
},
[]
);
return debounce;
}
export default useDebounce;
使用方法
import React, { useState } from 'react';
import useDebounce from './useDebounce';
const MyComponent = () => {
// 创建防抖函数
const debouncedHandleChange = useDebounce(() => {
console.log('防抖触发了');
}, 500);
return (
{
debouncedHandleChange(e);
}}
/>
);
};