Skip to content

Instantly share code, notes, and snippets.

@louicoder
Last active September 14, 2022 13:12
Show Gist options
  • Save louicoder/f3941d4cf9c7762e1fab389eaa6b04ee to your computer and use it in GitHub Desktop.
Save louicoder/f3941d4cf9c7762e1fab389eaa6b04ee to your computer and use it in GitHub Desktop.
Debounce functionality for auto suggestion while typing
// function called when debounce executes
// Usually this is where you call you external api
const onDebounce = () => {
console.log('calling api....');
};
// Function that handles on change for your iinput
const onValueChanged = (e) => {
console.log('changing state....');
setState(e.target.value);
};
// function handles delay in execution for your other function debounce
const debounce = (func) => {
let timer;
return function (...args) {
const context = this;
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
func.apply(context, args);
}, 3000);
};
};
// Function that is called by input onChange Handler
const debounceHandler = React.useCallback(debounce(onDebounce), [<inputValue>]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment