使用hooks封装防抖节流

    1. import { useCallback, useRef, useEffect } from 'react';
    2. function useDebounce(fn, delay, dep = []) {
    3. const { current } = useRef({ fn, timer: null });
    4. useEffect(
    5. function () {
    6. current.fn = fn;
    7. },
    8. [fn],
    9. );
    10. return useCallback(function f(...args) {
    11. if (current.timer) {
    12. clearTimeout(current.timer);
    13. }
    14. current.timer = setTimeout(() => {
    15. current.fn(...args);
    16. }, delay);
    17. }, dep);
    18. }
    19. export default useDebounce;