Skip to content

Instantly share code, notes, and snippets.

@OlivierJM
Created October 6, 2022 07:40
Show Gist options
  • Save OlivierJM/13358a5a68e38d0d69c9eabd79a67b71 to your computer and use it in GitHub Desktop.
Save OlivierJM/13358a5a68e38d0d69c9eabd79a67b71 to your computer and use it in GitHub Desktop.
import { useEffect, useState } from 'react';
/**
* Debounce a value to avoid constant calls to the server
* @param value it can be a string or a number
* @param delay the amount in milliseconds that will be delayed
* @returns The give value debounced
*/
export default function useDebounceValue<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value);
useEffect(() => {
const delayHandler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(delayHandler);
};
}, [value, delay]);
return debouncedValue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment