Skip to content

Instantly share code, notes, and snippets.

@jmcmullen
Created March 9, 2020 01:19
Show Gist options
  • Save jmcmullen/9561e0bcd2f7998ec7f556b2627f7e88 to your computer and use it in GitHub Desktop.
Save jmcmullen/9561e0bcd2f7998ec7f556b2627f7e88 to your computer and use it in GitHub Desktop.
import { useState, useEffect } from 'react';
function useDebounce<T>(
initialValue: T,
time: number
): [T, T, React.Dispatch<T>] {
const [value, setValue] = useState<T>(initialValue);
const [debouncedValue, setDebouncedValue] = useState<T>(initialValue);
useEffect(() => {
const debounce = setTimeout(() => {
setDebouncedValue(value);
}, time);
return () => {
clearTimeout(debounce);
};
}, [value, time]);
return [debouncedValue, value, setValue];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment