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)

原创文章,作者:sunnyman218,如若转载,请注明出处:https://blog.ytso.com/269296.html

(0)
上一篇 2022年6月21日
下一篇 2022年6月21日

相关推荐

发表回复

登录后才能评论