React Hooks 手写防抖useDebounce


定义

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

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

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


const useDebounce = (...[fn, debounce, deps]: DebouncePropsType) => {
    const { current } = useRef<DebounceRefType>({ fn })


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

    return useCallback(
        function (this: any, ...args: any[]) {
            if (current.timer) {
                clearTimeout(current.timer)
                delete current.timer
            }

            current.timer = setTimeout(() => {
                current.fn.apply(this, args)
            }, debounce);
        },
        // eslint-disable-next-line
        [debounce, current, ...deps],
    )

}

export default useDebounce

使用

    const debounceFn = useDebounce(() => { console.log('run') },timeout, deps)

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/269297.html

(0)
上一篇 2022年6月21日 02:01
下一篇 2022年6月21日 02:05

相关推荐

发表回复

登录后才能评论