How to use throttle or debounce with React Hook?

后端 未结 17 992
甜味超标
甜味超标 2020-11-30 04:27

I\'m trying to use the throttle method from lodash in a functional component, e.g.:

const App = () => {
  const [value, setValue         


        
17条回答
  •  一生所求
    2020-11-30 05:17

    Here is an actual throttle hook. You can use in a screen or component for all of the functions you want to throttle, and they will share the same throttle. Or you can call useThrottle() multiple times and have different throttles for individual functions.

    Use like this:

    import useThrottle from '../hooks/useThrottle';
    
    const [navigateToSignIn, navigateToCreateAccount] = useThrottle([
            () => { navigation.navigate(NavigationRouteNames.SignIn) },
            () => { navigation.navigate(NavigationRouteNames.CreateAccount) }
        ])
    

    And the hook itself:

    import { useCallback, useState } from "react";
    
    // Throttles all callbacks on a component within the same throttle.  
    // All callbacks passed in will share the same throttle.
    
    const THROTTLE_DURATION = 500;
    
    export default (callbacks: Array<() => any>) => {
        const [isWaiting, setIsWaiting] = useState(false);
    
        const throttledCallbacks = callbacks.map((callback) => {
            return useCallback(() => {
                if (!isWaiting) {
                    callback()
                    setIsWaiting(true)
                    setTimeout(() => {
                        setIsWaiting(false)
                    }, THROTTLE_DURATION);
                }
            }, [isWaiting]);
        })
    
        return throttledCallbacks;
    }
    

提交回复
热议问题