Skip to content

Instantly share code, notes, and snippets.

@eralpkaraduman
Last active January 5, 2023 15:55
Show Gist options
  • Save eralpkaraduman/bbf2c3d64839c1338e3efc93ed4fdf06 to your computer and use it in GitHub Desktop.
Save eralpkaraduman/bbf2c3d64839c1338e3efc93ed4fdf06 to your computer and use it in GitHub Desktop.
useCallback with lodash's throttle
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