Last active
January 5, 2023 15:55
-
-
Save eralpkaraduman/bbf2c3d64839c1338e3efc93ed4fdf06 to your computer and use it in GitHub Desktop.
useCallback with lodash's throttle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { DependencyList, useCallback } from 'react'; | |
import { throttle } from 'lodash'; | |
export function useThrottledCallback<A extends Array<unknown>, R extends unknown>( | |
callback: ((...args: A) => R) | undefined, | |
wait: number, | |
extraDeps: DependencyList = [], | |
): (...args: A) => R | undefined { | |
return useCallback( | |
(...args) => { | |
const throttledCallback = callback ? throttle(callback, wait) : () => undefined; | |
return throttledCallback(...args); | |
}, | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
[callback, wait, ...extraDeps], | |
); | |
} | |
// Usage | |
const myCallback = useThrottledCallback((param: string) => { | |
doSomething(param); // This will happen every other 200 ms | |
}, 200, [doSomething]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment