Skip to content

Instantly share code, notes, and snippets.

@apherio
Created February 28, 2021 14:03
Show Gist options
  • Save apherio/7034d3279384e4779cd57c17848a0d5c to your computer and use it in GitHub Desktop.
Save apherio/7034d3279384e4779cd57c17848a0d5c to your computer and use it in GitHub Desktop.
debouncing functionality.
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