Skip to content

Instantly share code, notes, and snippets.

@julioxavierr
Created December 11, 2019 12:22
Show Gist options
  • Save julioxavierr/965fd5551cdb981a8305d006740ac034 to your computer and use it in GitHub Desktop.
Save julioxavierr/965fd5551cdb981a8305d006740ac034 to your computer and use it in GitHub Desktop.
useDebounce hook with TS + underscorejs
import { useState, useEffect } from 'react';
import _ from 'underscore';
const DEFAULT_DEBOUNCE_TIMEOUT = 1000;
/**
* Debounce fast changing value.
* The debounced value will only reflect the latest value when the hook has not been called for the specified time period.
*/
function useDebounce(
value: any,
wait: number = DEFAULT_DEBOUNCE_TIMEOUT,
immediate?: boolean,
) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const debouncedFn = _.debounce(
() => setDebouncedValue(value),
wait,
immediate,
);
debouncedFn();
// Cancel the timeout if value changes
// Timeout gets cleared and restarted
return () => {
debouncedFn.cancel();
};
}, [immediate, value, wait]); // Only re-call effect if value or delay changes
return debouncedValue;
}
export default useDebounce;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment