Created
September 4, 2020 21:58
-
-
Save dknr/c39f96ad01c62c9cc1f10c3f6c13c4cc to your computer and use it in GitHub Desktop.
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
/* | |
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