Skip to content

Instantly share code, notes, and snippets.

@n1ru4l
Last active June 7, 2019 10:43
Show Gist options
  • Save n1ru4l/9b31487db9ac0847eb82b07f653e329c to your computer and use it in GitHub Desktop.
Save n1ru4l/9b31487db9ac0847eb82b07f653e329c to your computer and use it in GitHub Desktop.
Debounce Input Value Hook
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