整理一下react hooks版本的 防抖节流

防抖

害怕忘记,手写一遍,记录一下;

import React, { useRef, useCallback, useEffect } from 'react';
export const useDebounce=(fn,delay,dep=[]){
    const { current }=useRef({ fn,timer:null });
    useEffect(()=>{
       current.fn=fn;
    },[fn])
    return useCallback((...args)=>{
        if(current.timer){
             clearTimer(current.timer);
        }
        current.timer=setTimeout(()=>{
             current.fn(...args)
        },delay);
    },dep)
}

节流

   import React, { useCallback, useRef, useEffect } from 'react';
   export const useThrottle=(fn, delay, dep=[])=>{
       const { current }=useRef({ fn, timer:null });
       useEffect(()=>{
          current.fn=fn;
       },[fn])
       return useCallback((...args)=>{
           if(!current.timer){
                current.timer=setTimeout(()=>{
                    delete current.timer;
                },delay);
                current.fn(...args);
           }
       },dep);
   }

你可能感兴趣的:(react.js,javascript,前端)