From 2c6c281568c775d64ef9918d1b435582f86db90e Mon Sep 17 00:00:00 2001 From: Justin Date: Tue, 9 Aug 2022 14:19:19 -0400 Subject: [PATCH] Add "useDebounce" hook --- app/soapbox/hooks/index.ts | 1 + app/soapbox/hooks/useDebounce.ts | 17 +++++++++++++++++ 2 files changed, 18 insertions(+) create mode 100644 app/soapbox/hooks/useDebounce.ts diff --git a/app/soapbox/hooks/index.ts b/app/soapbox/hooks/index.ts index 4d7417771..7729fdf28 100644 --- a/app/soapbox/hooks/index.ts +++ b/app/soapbox/hooks/index.ts @@ -2,6 +2,7 @@ export { useAccount } from './useAccount'; export { useApi } from './useApi'; export { useAppDispatch } from './useAppDispatch'; export { useAppSelector } from './useAppSelector'; +export { useDebounce } from './useDebounce'; export { useDimensions } from './useDimensions'; export { useFeatures } from './useFeatures'; export { useLocale } from './useLocale'; diff --git a/app/soapbox/hooks/useDebounce.ts b/app/soapbox/hooks/useDebounce.ts new file mode 100644 index 000000000..ca324d788 --- /dev/null +++ b/app/soapbox/hooks/useDebounce.ts @@ -0,0 +1,17 @@ +import { useEffect, useState } from 'react'; + +const useDebounce = (value: string, delay: number): string => { + const [debouncedValue, setDebouncedValue] = useState(value); + + useEffect(() => { + const timer = setTimeout(() => setDebouncedValue(value), delay); + + return () => { + clearTimeout(timer); + }; + }, [value, delay]); + + return debouncedValue; +}; + +export { useDebounce };