其他分享
首页 > 其他分享> > React Hooks 手写节流useThrottle

React Hooks 手写节流useThrottle

作者:互联网

定义

import { useCallback, useEffect, useRef } from "react"

export interface ThrottleRefType {
    fn: Function,
    timer?: NodeJS.Timeout
}

export type ThrottlePropsType = [Function, number, Array<any>]


const useThrottle = (...[fn, throttle, deps]: ThrottlePropsType) => {

    const { current } = useRef<ThrottleRefType>({ fn })

    useEffect(() => {
        current.fn = fn
    }, [fn, current])

    return useCallback(
        function (this: any, ...args: any[]) {
            if (!current.timer) {
                current.timer = setTimeout(() => {
                    current.fn.apply(this, Array.from(args))
                    delete current.timer
                }, throttle)
            }
        },
        // eslint-disable-next-line
        [...deps, current, throttle]
    )
}

export default useThrottle

使用

    const throttleFn = useThrottle(() => { console.log('run') },timeout, deps)

标签:current,useThrottle,const,Hooks,timer,React,export,fn
来源: https://www.cnblogs.com/ltfxy/p/16395299.html