Last active
June 7, 2019 10:43
-
-
Save n1ru4l/9b31487db9ac0847eb82b07f653e329c to your computer and use it in GitHub Desktop.
Debounce Input Value Hook
This file contains hidden or 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
| import { useEffect, useState } from "react"; | |
| const useDebouncedInputValue = ( | |
| initialValue: string, | |
| debounceDuration: number = 200 | |
| ): [string, string, (val: string) => void] => { | |
| const [currentValue, setCurrentValue] = useState(initialValue); | |
| const [debouncedValue, setDebouncedValue] = useState(currentValue); | |
| useEffect(() => { | |
| let timeout = setTimeout(() => { | |
| setDebouncedValue(currentValue); | |
| }, debounceDuration); | |
| return () => { | |
| clearTimeout(timeout); | |
| }; | |
| }, [currentValue, setDebouncedValue, debounceDuration]); | |
| return [currentValue, debouncedValue, setCurrentValue]; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment