[Vue3][React]自定义hooks实现防抖节流

参考资料:

js防抖、节流(立即执行/非立即执行 + 立即取消等待)

https://blog.csdn.net/qq1361200/article/details/112253863

debounce防抖

普通实现

function debounce(fn, ms) {
  let timer;
  return function (...args) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn(...args)
      timer = null;
    }, ms);
  }
}

react自定义hooks

每次组件重新渲染,都会执行一遍所有的hooks,这样debounce高阶函数里面的timer就不能起到缓存的作用(每次重渲染都被置空),timer不可靠,debounce的核心就被破坏了,所以需要useCallback缓存函数

import {useState, useEffect, useRef, useCallback} from 'react'


export function useDebounce(fn, delay, dep = []) {
  const {current} = useRef({fn, timer: null});
  useEffect(function () {
    current.fn = fn;
  }, [fn]);

  return useCallback(function f(...args) {
    if (current.timer) {
      clearTimeout(current.timer);
    }
    current.timer = setTimeout(() => {
      current.fn.call(this, ...args);
    }, delay);
  }, dep)
}

vue3自定义hooks

import {
  costomRef
} from 'vue'

export function debouncedRef(value, delay = 200) {
  let timeout;
  return costomRef((track, trigger) => {
    return {
      get() {
        track()
        return value
      },
      set(newValue) {
        clearTimeout(timeout)
        timeout = setTimeout(() => {
          value = newValue;
          trigger()
        }, delay)
      }
    }
  })
}

throttle节流

普通实现

function debounce(fn, ms) {
  let flag = true;
  return function (...args) {
    if (flag) {
       flag = false
       let timer = setTimeout(()=>{
         fn.apply(this,arguments)
         flag = true
       }, ms)
    }
  }
}

react自定义hooks

function useThrottle(fn, delay, dep = []) {
  const { current } = useRef({ fn, timer: null });
  useEffect(function () {
    current.fn = fn;
  }, [fn]);
 
  return useCallback(function f(...args) {
    if (!current.timer) {
      current.timer = setTimeout(() => {
        delete current.timer;
      }, delay);
      current.fn.call(this, ...args);
    }
  }, dep);
}

vue3自定义hooks

import {
  costomRef
} from 'vue'

export function throttleRef(value, delay = 200) {
  let flag = true;
  return costomRef((track, trigger) => {
    return {
      get() {
        track()
        return value
      },
      set(newValue) {
        if (flag) {
           flag = false
           let timer = setTimeout(()=>{
             	value = newValue;
          		trigger()
             flag = true
           }, ms)
        }
      }
    }
  })
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值