Skip to content

Instantly share code, notes, and snippets.

@dknr
Created September 4, 2020 21:58
Show Gist options
  • Save dknr/c39f96ad01c62c9cc1f10c3f6c13c4cc to your computer and use it in GitHub Desktop.
Save dknr/c39f96ad01c62c9cc1f10c3f6c13c4cc to your computer and use it in GitHub Desktop.
/*
debounce setState to prevent input lag
use the returned immediateValue for the input's value prop, and value for filter, etc.
*/
export const useDebouncedState = <T>(initialState: T, timeout: number) => {
const [value, setValue] = useState(initialState);
const [immediateValue, setImmediateValue] = useState(initialState);
const [timeoutId, setTimeoutId] = useState(undefined as undefined | any);
const setDebouncedValue = (newValue: T) => {
setImmediateValue(newValue);
if (timeoutId) {
clearTimeout(timeoutId);
}
setTimeoutId(setTimeout(() => {
setValue(newValue);
}, timeout));
}
return [value, setDebouncedValue, immediateValue];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment